One optional argument which does not require positional arguments

后端 未结 3 2010
抹茶落季
抹茶落季 2021-02-10 23:02

I have a question regarding python\'s argparse: Is it possible to have a optional argument, which does not require positional arguments?

Example:

parser.         


        
3条回答
  •  清酒与你
    2021-02-10 23:50

    • set a default value and nargs='?' for your positional arguments
    • check manually in your code that both latitude and longitude have been set when you're not in list-methods mode

      parser = argparse.ArgumentParser()
      
      parser.add_argument('lat', help="latitude",default=None, nargs='?')
      parser.add_argument('lon', help="longitude",default=None, nargs='?')
      parser.add_argument('--method', help="calculation method (default: add)", default="add")
      parser.add_argument('--list-methods', help="list available methods", action="store_true")
      
      args = vars(parser.parse_args())
      
      if not args['list_methods'] and (args['lat'] == None or args['lon'] == None):
          print '%s: error: too few arguments' % sys.argv[0]
          exit(0)
      
      if args['list_methods']:
          print 'list methods here'
      else :
          print 'normal script execution'
      

    which gives :

    $ test.py --list-methods
    list methods here

    $ test.py 4
    test.py: error: too few arguments

    test.py 4 5
    normal script execution

提交回复
热议问题