标题可能令人困惑,但我想不出更好的解释。基本上,我有一个程序可以对带有一堆可选参数的输入文件进行操作。输入文件对于我的程序是强制性的。所以我写了一个这样的解析器:
测试.py
from argparse import ArgumentParser
parser = ArgumentParser(prog="prog")
parser.add_argument("file", help="input file")
parser.add_argument("--debug", action="store_true", help="enable debug messages")
parser.parse_args()
为简单起见,我没有显示所有选项。现在,我想为这个程序添加一个不需要输入文件并自行运行的功能。让我们将此选项称为a
. Optiona
采用未知数量的参数,--debug
或者其他选项对 option 无效a
。因此,以下将是我的程序的有效运行:
$ python3 test.py input.txt $ python3 test.py input.txt --debug $ python3 test.py -a 1 2 3
这些将是无效的:
$ python3 test.py input.txt -a 1 2 3 $ python3 test.py -a 1 2 3 --debug
当我将此行添加到我的代码中时
parser.add_argument("-a", nargs="+", help="help option a")
它接受选项a
,但出于可以理解的原因,它说“需要文件”。那么我应该如何修改我的代码来实现我的目标呢?
PS:我也尝试过使用 subparser 但我无法让它按我想要的方式工作,可能是因为我缺乏知识。