将可选列表传递给argparse [英] Pass an optional list to argparse
问题描述
是否有一种更优雅的方式将可选的整数列表传递给argparse
?我也有一个立场论点.
Is there a more elegant way to pass an optional list of integers to argparse
than to pass a delimited string and parse it later? I also have a positional argument.
parser.add_argument('--ids', type=int, nargs='+')
parser.add_argument('cmd')
不起作用,因为argparse
尝试获取cmd
并抱怨它不是整数.
doesn't work, because argparse
attempts to grab cmd
and complains that it isn't an integer.
理想情况下,我想使用其中一个执行
Ideally, I'd like to execute with one of
program.py --ids 6,32,12 refresh
program.py --ids 6 32 12 refresh
或类似的东西,但也能够
or something similar, but also be able to
program.py refresh
推荐答案
如果您只想解析--ids 1,2,3
形式的参数(无空格),则可以使用以下方式:
If you just want to parse arguments of the form --ids 1,2,3
(no whitespace), you can use something like this:
def convert(argument):
return map(int, argument.split(',')) # 3.x: consider wrapping in list()
parser.add_argument('--ids', type=convert)
这不会处理用空格分隔的参数,尽管您可以使用更聪明的convert()
函数来缓解这种情况.然后,您需要引用它们,否则外壳会将它们作为单独的参数传递.
This will not handle arguments separated by whitespace, though you could probably mitigate that somewhat with a smarter convert()
function. You would then need to quote them, however, or else the shell would pass them as separate arguments.
这篇关于将可选列表传递给argparse的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!