-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:])
请勿使用getopt。使用argparse。 – 2014-09-21 17:04:23
我很惊讶'getopt'尚未被弃用。 – simonzack 2014-09-21 17:15:09
可能因为它从来没有打算成为解析选项的主要方法;它只是作为来自C的用户的垫脚石而已。这几乎是自我否定的:) – chepner 2014-09-21 17:32:25