我是否也应该用getopt(...)解析必需参数

1 投票
2 回答
2231 浏览
提问于 2025-04-16 22:37
"""
Saves a dir listing in a file
Usage: python listfiles.py -d dir -f filename [flags]
Arguments:
  -d, --dir               dir; ls of which will be saved in a file
  -f, --file              filename (if existing will be overwritten)
Flags:
  -h, --help              show this help 
  -v, --verbose           be verbose
"""         

...

def usage():
  print __doc__

def main(args):
  verbose = False
  srcdir = filename = None
  try:
    opts, args = getopt.getopt(args,
                               'hvd:f:', ['help', 'verbose', 'dir=', 'file='])
  except getopt.GetoptError:
    usage()
    sys.exit(2)
  for opt, arg in opts:
    if opt in ('-h', '--help'):
      usage()
      sys.exit(0)
    if opt in ('-v', '--verbose'):
      verbose = True
    elif opt in ('-d', '--dir'):
      srcdir = arg
    elif opt in ('-f', '--file'):
      filename = arg
  if srcdir and filename:
    fsock = open(filename, 'w')
    write_dirlist_tosock(srcdir, fsock, verbose)
    fsock.close()
  else:
    usage()
    sys.exit(1)

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

我不太确定用 getopt() 来处理必填参数是否符合 Python 的风格。希望能得到一些建议。

2 个回答

1

“强制选项”这个说法其实是自相矛盾的,而且大多数选项解析库对它的支持也不太好。你应该考虑把强制参数作为位置参数来处理,而不是通过选项解析器来解析,这样做更符合常规做法。

3

这个 getopt 模块主要是给那些已经了解C语言中同样模块的用户使用的。对于大多数人来说,Python里处理参数的标准方法是argparse

撰写回答