[英]How to pass and parse a list of strings from command line with argparse.ArgumentParser in Python?
I want to pass a list of names into my program written in Python from console. 我想将一个名称列表传递给我从控制台用Python编写的程序。 For instance, I would like to use a way similar to this (I know it shouldn't work because of
bash
): 例如,我想使用类似于此的方式(我知道它不应该因为
bash
而工作):
$ python myprog.py -n name1 name2
So, I tried this code: 所以,我尝试了这段代码:
# myprog.py
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument('-n', '--names-list', default=[])
args = parser.parse_args()
print(args.names_list) # I need ['name1', 'name2'] here
That led to the error: 这导致了错误:
usage: myprog.py [-h] [-n NAMES_LIST]
myprog.py: error: unrecognized arguments: name2
I know I could pass the names with quotes "name1 name2"
and split it in my code args.names_list.split()
. 我知道我可以使用引号
"name1 name2"
传递名称,并将其拆分为我的代码args.names_list.split()
。 But I'm curious, is there a better way to pass the list of strings via argparse
module. 但我很好奇,有没有更好的方法通过
argparse
模块传递字符串列表。
Any ideas would be appreciated. 任何想法,将不胜感激。
Thanks! 谢谢!
You need to define --names-list
to take an arbitrary number of arguments. 您需要定义
--names-list
以获取任意数量的参数。
parser.add_argument('-n', '--names-list', nargs='+', default=[])
Note that options with arbitrary number of arguments don't typically play well with positional arguments, though: 请注意,具有任意数量参数的选项通常不能很好地与位置参数一起使用,但是:
# Is this 4 arguments to -n, or
# 3 arguments and a single positional argument, or ...
myprog.py -n a b c d
You need to use nargs
: 你需要使用
nargs
:
parser.add_argument('-n', '--names-list', nargs="*")
https://docs.python.org/3/library/argparse.html#nargs https://docs.python.org/3/library/argparse.html#nargs
parser.add_argument('-n', '--names-list', default=[], nargs='+')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.