usage函数在getopt中无效

6 投票
1 回答
22124 浏览
提问于 2025-04-17 03:06

我在使用Python的时候遇到了一个问题。这里是我主函数的一部分:

def main(argv):
    try:
            opts, args = getopt.getopt(argv, 'hi:o:tbpms:', ['help', 'input=', 'output='])
            if not opts:
                    print 'No options supplied'
                    usage()
    except getopt.GetoptError,e:
           print e
           usage()
           sys.exit(2)

    for opt, arg in opts:
            if opt in ('-h', '--help'):
                    usage()
                   sys.exit(2)
if __name__ =='__main__':
    main(sys.argv[1:])

我也定义了一个使用说明的函数

def usage():
    print "\nThis is the usage function\n"
    print 'Usage: '+sys.argv[0]+' -i <file1> [option]'

但是当我运行我的代码,比如用 ./code.py 或者 ./code.py -h(这个文件是可以执行的)时,我得到的却不是Python的帮助信息。

1 个回答

8

下面的代码对我有效。用“python code.py”来运行它。

import getopt, sys

def usage():
  print "\nThis is the usage function\n"
  print 'Usage: '+sys.argv[0]+' -i <file1> [option]'

def main(argv):
  try:
    opts, args = getopt.getopt(argv, 'hi:o:tbpms:', ['help', 'input=', 'output='])
    if not opts:
      print 'No options supplied'
      usage()
  except getopt.GetoptError,e:
    print e
    usage()
    sys.exit(2)

  for opt, arg in opts:
    if opt in ('-h', '--help'):
      usage()
      sys.exit(2)

if __name__ =='__main__':
    main(sys.argv[1:])

撰写回答