Python argparse: Require two corequisite positional arguments

后端 未结 1 1919
天命终不由人
天命终不由人 2021-01-28 21:26

Using argparse, how do I specify that I want two positional arguments to appear together or not at all? I.e. I want my usage string to look like:



        
相关标签:
1条回答
  • 2021-01-28 21:50

    As suggested by @hpaulj, here's a solution you could use:

    In [1]: import argparse
    In [2]: parser = argparse.ArgumentParser(description="bla bla")
    In [3]: parser.add_argument("--foo", nargs=2, help="a foo argument")
    
    In [4]: parser.parse_args(["--foo", "1", "2"])
    Out[4]: Namespace(foo=['1', '2'])
    
    In [5]: parser.parse_args([])
    Out[5]: Namespace(foo=None)
    
    In [6]: parser.print_help()
    usage: ipython [-h] [--foo FOO FOO]
    
    bla bla
    
    optional arguments:
      -h, --help     show this help message and exit
      --foo FOO FOO  a foo argument
    
    0 讨论(0)
提交回复
热议问题