import argparse
parser = argparse.ArgumentParser()
# By default it will fail with multiple arguments.
parser.add_argument('--default')
# Telling the type to be a list will also fail for multiple arguments,
# but give incorrect results for a single argument.
parser.add_argument('--list-type', type=list)
# This will allow you to provide multiple arguments, but you will get
# a list of lists which is not desired.
parser.add_argument('--list-type-nargs', type=list, nargs='+')
# This is the correct way to handle accepting multiple arguments.
# '+' == 1 or more.
# '*' == 0 or more.
# '?' == 0 or 1.
# An int is an explicit number of arguments to accept.
parser.add_argument('--nargs', nargs='+')
# To make the input integers
parser.add_argument('--nargs-int-type', nargs='+', type=int)
# An alternate way to accept multiple inputs, but you must
# provide the flag once per input. Of course, you can use
# type=int here if you want.
parser.add_argument('--append-action', action='append')
# To show the results of the given option to screen.
for _, value in parser.parse_args()._get_kwargs():
if value is not None:
print(value)
TL;DR
使用
nargs
选项或action
选项的'append'
设置(取决于您希望用户界面的行为方式)。纳格斯
nargs='+'
接受一个或多个参数,nargs='*'
接受零个或多个参数。追加
使用
append
可以多次提供选项来构建列表。不要使用
type=list
!!!-在这种情况下,您可能不想将type=list
与argparse
一起使用。永远。让我们更详细地了解一下人们可能尝试的一些不同方法,以及最终的结果。
以下是您可以预期的输出:
外卖:
nargs
或action='append'
nargs
从用户的角度来看可能更直接,但是如果有位置参数,则可能是不直观的,因为argparse
无法区分什么应该是位置参数,什么应该属于nargs
;如果有位置参数,则action='append'
可能会成为更好的选择。nargs
、'+'
、或'?'
时,以上才是正确的。如果您提供一个整数(例如4
),那么将选项与nargs
和位置参数混合将不会有问题,因为argparse
将确切知道该选项需要多少值。type=list
,因为它将返回列表列表argparse
使用type
的值来强制每个给定的参数您选择的type
,而不是所有参数的集合。type=int
(或其他)来获取int列表(或其他)1:我不是一般意义上的。。我的意思是用引号将列表传递给
argparse
不是你想要的。除了^{} 之外,如果事先知道列表,您可能还需要使用^{} :
我更喜欢传递一个分隔字符串,稍后在脚本中解析它。原因是:列表可以是任何类型的
int
或str
,如果有多个可选参数和位置参数,有时使用nargs
会遇到问题。那么
或者
会起作用的。分隔符也可以是一个空格,尽管它会像在问题的示例中那样在参数值周围强制使用引号。
相关问题 更多 >
编程相关推荐