带有getopt的Python命令行arg不起作用

时间:2014-09-21 17:03:13

标签: python getopt

我修改了这里给出的示例代码: sample code for getopt

如下,但它不起作用。我不确定我错过了什么。我添加了一个" -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:])

1 个答案:

答案 0 :(得分: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模块。

相关问题