如何在 Python 脚本中为 getopt 添加帮助用法

How to add help usage in Python script for getopt

考虑:

    import getopt

    options, remainder = getopt.getopt(sys.argv[1:], 'd:a', ['directory=',
                                                     'algorithm',
                                                     'version=',
                                                     ])
    print 'OPTIONS   :', options

    for opt, arg in options:
      if opt in ('-d', '--dir'):
        directory_path = arg
      elif opt in ('-a', '--alg'):
        algorithm = arg
      elif opt == '--version':
        version = arg

这个脚本工作正常,但是如果用户没有指定任何参数(-d 选项是必须的),我如何指定它并使程序继续而不退出并出现错误:因为没有指定文件路径

如果用户不知道哪些参数可用,我该如何显示喜欢的帮助或用法?

您可以定义一个新的帮助函数并在需要时显示它

def help():
  print(...)

...
for opt, arg in options:
  if opt in ('-d', '--dir'):
    directory_path = arg
  else:
    help()

您可以实现以下目标:

import sys
import getopt

def usage():
    print '<program.py> -i infile | -o outfile | -h help'

def mymethod(argv):
 inputfile=''
 outputfile=''
 if(len(argv)<2):
  usage()
  sys.exit(2)
 try:
  opts, args = getopt.getopt(argv, "i:o:h",["ifile=", "ofile=","help="])
 except getopt.GetoptError:
  usage()
  sys.exit(2)
 for opt, arg in opts:
  if opt == '-h':
   usage()
   sys.exit()
  elif opt in ("-i", "--ifile"):
   print 'input file name is ', arg
  if opt in ("-o", "--ofile"):
   print 'output file name is ', arg
if __name__=='__main__':
        mymethod(sys.argv[1:])