Python argparse列表输入 [英] Python argparse a list input

查看:313
本文介绍了Python argparse列表输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码接受mode的命令行参数,例如-m fizz-m fizz bazz.如预期的那样,这会将参数作为['fizz', 'bazz']传递给主函数(对于上面的第二个示例).传递带有空格的命令行参数似乎对用户不友好,因此我希望argparse接受以逗号分隔的列表,例如-m fizz,bazz-m ['fizz','bazz'].如何修改下面的代码来做到这一点?谢谢!

The code below accepts command line arguments for mode such as -m fizz and -m fizz bazz. This, as expected, passes the arguments to the main function as ['fizz', 'bazz'] (for the second example above). It seems user-unfriendly to pass command line arguments with spaces, so I'd like argparse to accept a comma-separated list e.g. -m fizz,bazz or -m ['fizz','bazz']. How can I modify the code below to do this? Thanks!

import agrparse
...
parser.add_argument("-m", "--mode", nargs="*",
                    default=["fizz", "bazz", "razmataz"],
                    help="Comma separated list of mode(s) to use, e.g."
                    "[\"fizz\", \"bazz\"]")
main(parser.parse_args())

推荐答案

使用打印sys.argv我得到的简单脚本

With a simple script that prints sys.argv I get

1014:~/mypy$ python echoargv.py -m ['fizz','bazz']
['echoargv.py', '-m', '[fizz,bazz]']
1014:~/mypy$ python echoargv.py -m fizz,bazz
['echoargv.py', '-m', 'fizz,bazz']
1015:~/mypy$ python echoargv.py -m fizz, bazz
['echoargv.py', '-m', 'fizz,', 'bazz']
1016:~/mypy$ python echoargv.py -m ['fizz', 'bazz']
['echoargv.py', '-m', '[fizz,', 'bazz]']
1016:~/mypy$ python echoargv.py -m fizz bazz
['echoargv.py', '-m', 'fizz', 'bazz']

这就是您的parser必须使用的.

That's what your parser has to work with.

最后一种情况(每个字符串是sys.argv中的单独项目)最简单,这是您的nargs='*'旨在处理的情况.它应该返回Namespace(mode = ['fizz','bazz'])

The last case, where each string is a separate item in the sys.argv is simplest, and is what your nargs='*' is designed to handle. It should return Namespace(mode = ['fizz','bazz'])

您有2个选择.您可以在将sys.argv传递给parser之前对其进行清理.或者,您可以在解析后查看args.mode属性,并根据需要对其进行清理.

You have 2 options. You could clean up sys.argv before passing it to the parser. Or you could look at the args.mode attribute after parsing, and clean it up as needed.

例如,'fizz,bazz'可以在,上拆分. '[fizz,bazz]'需要首先剥离[].其他人则需要删除多余的,'.

For example 'fizz,bazz' could be split on ,. '[fizz,bazz]' requires stripping off the [] first. Others require removing extra ,'.

您可以在自定义的Action类中进行此拆分和清理,但这不会为您节省任何工作.

You could do this splitting and cleanup in a custom Action class, but it isn't going to save you any work.

自定义type也可以用于拆分字符串

A custom type could also be used to split strings

In [170]: def foolist(astring):
    alist=astring.strip('[').strip(']').split(',')
    alist = [a.strip() for a in alist if len(a)]
    return alist

In [171]: p=argparse.ArgumentParser()

In [172]: p.add_argument('-m',type=foolist,nargs='*')
Out[172]: _StoreAction(option_strings=['-m'], dest='m',...

In [173]: p.parse_args(['-m','one','two'])
Out[173]: Namespace(m=[['one'], ['two']])

In [174]: p.parse_args(['-m','one,two'])
Out[174]: Namespace(m=[['one', 'two']])

In [175]: p.parse_args(['-m','[one, two]'])
Out[175]: Namespace(m=[['one', 'two']])

列表嵌套的缺点.可以使用默认的nargs,但不允许使用常规的空格分隔列表.但是有一些扁平化嵌套列表的标准python方法.

A down side to this that the lists are nested. The default nargs could be used, but it wouldn't allow the regular space delimited lists. But there are standard python ways of flattening a nested list.

这篇关于Python argparse列表输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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