Skip to main content
 首页 » 编程设计

python之无法使用getopt python处理参数

2025年05月04日11youxin

为了给我的 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:]) 

请您参考如下方法:

我建议添加更多日志记录。这不仅会在现在帮助您,还会在将来帮助任何使用您的脚本的人。

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) 

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