将可选列表传递给 argparse [英] Pass an optional list to argparse

查看:31
本文介绍了将可选列表传递给 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

或类似的东西,但也能

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() 函数来缓解这种情况.但是,您随后需要引用它们,否则 shell 会将它们作为单独的参数传递.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆