且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

一种可选的参数,不需要位置参数

更新时间:2022-06-19 09:53:57

  • 设置默认值,并为位置参数设置nargs='?'
  • 在代码中手动检查未处于 list-methods 模式时是否已设置了纬度经度

    • 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'
      

    • 给出:

      $ test.py --list-methods
      在此处列出方法

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

      $ test.py 4
      test.py:错误:参数太少

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

      test.py 4 5
      正常脚本执行

      test.py 4 5
      normal script execution