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

Ani*_*ilJ -1 python getopt

我修改了此处给出的示例代码: getopt 的示例代码

如下,但它不起作用。我不确定我错过了什么。我在现有代码中添加了“-j”选项。最终,我想添加尽可能多的命令选项以满足我的需求。

当我提供如下输入时,它不会打印任何内容。

./pyopts.py -i dfdf -j qwqwqw -o ddfdf
Input file is " 
J file is " 
Output file is " 
Run Code Online (Sandbox Code Playgroud)

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

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

Yoe*_*oel 5

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

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

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

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

使用指定的参数执行它会得到预期的输出:

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

但是,正如对您的问题的评论所指定的那样,您应该使用argparse而不是getopt

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