如何允许 -non_number 作为 python argparse 中的参数

how to allow -non_number as arguments in python argparse

python test.py --arg -foo -bar
test.py: error: argument --arg: expected at least one argument

python test.py --arg -8
['-8']

如何允许 -non_number 使用 argparse?

有没有办法禁用短参数?

我认为您正在寻找 argparser 的 nargs 参数。

parser.add_argument('--arg', nargs='?')

目前,--arg 将值 '-8' 解释为输入,而它认为 '-f'(带有参数 'oo')是一个新参数。

或者,您可以使用 action='store_true',它将用布尔值表示参数是否存在。

parser.add_argument('--arg', action='store_true')

https://docs.python.org/3/library/argparse.html#nargs

这样称呼它:

python test.py --arg='-foo'

允许指定多个:

parser.add_argument('--arg', action='append')
# call like python test.py --arg=-foo --arg=-bar