无法使用getopt python处理参数

Ale*_*dro 1 python getopt

为了给我的python脚本提供选项,我想介绍一些参数.我发现在python中更好的方法是使用getopt,但是一旦我运行我的脚本它就什么都不做.请帮我!!!.这是我的代码:

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:])
Run Code Online (Sandbox Code Playgroud)

Joh*_*web 5

我建议添加更多日志记录.这不仅可以帮助您,也可以帮助您将来使用您的脚本.

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)
Run Code Online (Sandbox Code Playgroud)

我还将调用maininfo()移出了循环,因为你可以-t在文件名之前提供!