Python argparse: Require two corequisite positional arguments

会有一股神秘感。 提交于 2019-12-25 04:09:44

问题


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:

Usage: FooBar.py [-h] [FOO BAR]

回答1:


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


来源:https://stackoverflow.com/questions/39598489/python-argparse-require-two-corequisite-positional-arguments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!