2014-09-21 39 views
-1

我修改这里给出的示例代码: sample code for getopt与getopt的Python的命令行参数不起作用

如下,但它不工作。我不知道我错过了什么。我为这个现有的代码添加了一个“-j”选项。最终,我想添加尽可能多的命令选项以满足我的需求。

当我输入如下,它不会打印任何东西。

./pyopts.py -i dfdf -j qwqwqw -o ddfdf 
Input file is " 
J file is " 
Output file is " 

请问我能告诉我这里有什么问题吗?

#!/usr/bin/python 

import sys, getopt 

def usage(): 
    print 'test.py -i <inputfile> -j <jfile> -o <outputfile>' 

def main(argv): 
    inputfile = '' 
    jfile = '' 
    outputfile = '' 
    try: 
     opts, args = getopt.getopt(argv,"hij:o:",["ifile=","jfile=","ofile="]) 
    except getopt.GetoptError: 
     usage() 
     sys.exit(2) 
    for opt, arg in opts: 
     if opt == '-h': 
     usage() 
     sys.exit() 
     elif opt in ("-i", "--ifile"): 
     inputfile = arg 
     elif opt in ("-j", "--jfile"): 
     jfile = arg 
     elif opt in ("-o", "--ofile"): 
     outputfile = arg 

    print 'Input file is "', inputfile 
    print 'J file is "', jfile 
    print 'Output file is "', outputfile 

if __name__ == "__main__": 
    main(sys.argv[1:]) 
+4

请勿使用getopt。使用argparse。 – 2014-09-21 17:04:23

+0

我很惊讶'getopt'尚未被弃用。 – simonzack 2014-09-21 17:15:09

+0

可能因为它从来没有打算成为解析选项的主要方法;它只是作为来自C的用户的垫脚石而已。这几乎是自我否定的:) – chepner 2014-09-21 17:32:25

回答

4

您的错误在i选项后面省略冒号。正如您提供的链接所述:

需要参数的选项后面应跟冒号(:)。

因此,你的程序的修正版本应包含以下内容:

try: 
     opts, args = getopt.getopt(argv,"hi:j:o:",["ifile=","jfile=","ofile="]) 
    except getopt.GetoptError: 
     usage() 
     sys.exit(2) 

用指定的参数执行它获得预期的输出:

~/tmp/so$ ./pyopts.py -i dfdf -j qwqwqw -o ddfdf 
Input file is " dfdf 
J file is " qwqwqw 
Output file is " ddfdf 

但是,作为一个评论您的问题指定,您应该使用argparse而不是getopt

注意: getopt模块是命令行选项的解析器,其API设计为让C getopt()函数的用户熟悉。不熟悉C getopt()函数的用户,或者希望编写更少代码并获得更好帮助和错误消息的用户应该考虑使用argparse模块。