【问题标题】:Using Python3 and the argparse module, can I disallow an argument if a different one was passed?使用 Python3 和 argparse 模块,如果传递了不同的参数,我可以禁止参数吗?
【发布时间】:2015-09-20 11:56:52
【问题描述】:

例如,假设用户传递了一个参数,例如

python3 myscript.py -a

而且我也希望他们能够通过

python3 myscript.py -b

但我希望他们能够同时通过两个例如

python3 myscript.py -a -b

我该怎么做呢?我对 argparse 还不太熟悉,文档有点难以理解。

非常感谢:)

【问题讨论】:

标签: python python-3.x argparse command-line-arguments


【解决方案1】:

你想要一个mutually exclusive group 的参数。这是一个最小的例子:

import argparse
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()
group.add_argument('-a', help='Do A', action='store_true')
group.add_argument('-b', help='Do B', action='store_true')
args = parser.parse_args()
if args.a:
    print('A!')
if args.b:
    print('B!')

测试:

$ python myscript.py -h
usage: myscript.py [-h] [-a | -b]

optional arguments:
  -h, --help  show this help message and exit
  -a          Do A
  -b          Do B
$ python myscript.py -a
A!
$ python myscript.py -b
B!
$ python myscript.py -a -b
usage: myscript.py [-h] [-a | -b]
myscript.py: error: argument -b: not allowed with argument -a

【讨论】:

  • 完美,正是我想要的!谢谢:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-16
  • 2021-06-27
相关资源
最近更新 更多