开发者

Should I also parse mandatory arguments with getopt(...)

开发者 https://www.devze.com 2023-03-25 10:56 出处:网络
\"\"\" Saves a dir listing in a file Usage: python listfiles.py -d dir -f filename [flags] Arguments: -d, --dirdir; ls of which will be saved in a file
"""
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 us开发者_StackOverflow中文版age():
  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:])  

I am not sure if it is pythonic to use getopt() to also handle mandatory arguments. Would appreciate some suggestions


the getopt module is only for those users who are already familiar with the same module in C, the python standard argument handling is argparse.


"Mandatory Options" is a contradiction, and is not generally well supported by the various option parsing libraries; You should consider placing mandatory arguments as a positional arguments, not parsed by the option parser, this would agree with common practice much better.

0

精彩评论

暂无评论...
验证码 换一张
取 消