开发者

Cannot handle parameters with getopt python

开发者 https://www.devze.com 2023-03-27 16:20 出处:网络
In order to offer options tomy python script, I want to introduce some parameters. I found that the better way to do this in python is with 开发者_开发技巧getopt, but once I run my script it doesn\'t

In order to offer options to my python script, I want to introduce some parameters. I found that the better way to do this in python is with 开发者_开发技巧getopt, but once I run my script it doesn't do anything. Please help me!!!. This is my code:

def main(argv):
     try:
            opts, args = getopt.getopt(argv, 'hi:o:t', ['help', 'input=', 'output='])
    except getopt.GetoptError:
            usage()
            sys.exit(2)
            file = None
            outfile = None
    for opt, arg in opts:
            if opt in ('-h', '--help'):
                    usage()
                    sys.exit(2)
            elif opt in ('-i', '--input'):
                    file = arg
            elif opt in ('-o', '--output'):
                    outfile = arg
            elif opt == '-t':
                    maininfo(file,outfile)
            else:
                    usage()
                    sys.exit(2)

if __name__ =='__main__':
    main(sys.argv[1:])


I suggest adding more logging. Not only will this help you out now, it'll help out whoever uses your script in future.

def main(argv):
    filename = None
    outfile = None
    call_maininfo = False
    try:
        opts, args = getopt.getopt(argv, 'hi:o:t', ['help', 'input=', 'output='])
        if not opts:
            print 'No options supplied'
            usage()
    except getopt.GetoptError, e:
        print e
        usage()
        sys.exit(2)
    for opt, arg in opts:
        if opt in ('-h', '--help'):
            usage()
            sys.exit(2)
        elif opt in ('-i', '--input'):
            filename = arg
        elif opt in ('-o', '--output'):
            outfile = arg
        elif opt == '-t':
            call_maininfo = True
        else:
            usage()
            sys.exit(2)

    print 'Processed options [{0}] and found filename [{1}] and outfile [{2}]'.format(
            ', '.join(argv),
            filename,
            outfile,
            )

    if call_maininfo:
        print 'Calling maininfo()'
        maininfo(filename, outfile)

I also moved the call to maininfo() out of the loop as you could supply -t before the filenames!


You can use optparse(old version, will be deprecated after python 2.7) or argparse ( a new version), which are standard python module parsing arguments.

Hope it helps this first


Please see this answer: https://stackoverflow.com/a/1540399/2542738

Basically, you need to remove 'python' from opts as it is the first element of the list opts: opts.pop(0) and then you should be fine.

0

精彩评论

暂无评论...
验证码 换一张
取 消