我试图将列表作为参数传递给命令行程序.是否有argparse选项将列表作为选项传递?

parser.add_argument('-l', '--list',
                      type=list, action='store',
                      dest='list',
                      help='<Required> Set flag',
                      required=True)

脚本的调用如下所示

python test.py -l "265340 268738 270774 270817"

推荐答案

SHORT ANSWER

使用nargs选项或action选项的'append'设置(取决于您希望用户界面的行为).

nargs

parser.add_argument('-l','--list', nargs='+', help='<Required> Set flag', required=True)
# Use like:
# python arg.py -l 1234 2345 3456 4567

nargs='+'接受1个或多个参数,nargs='*'接受0个或多个参数.

append

parser.add_argument('-l','--list', action='append', help='<Required> Set flag', required=True)
# Use like:
# python arg.py -l 1234 -l 2345 -l 3456 -l 4567

使用append,您可以多次提供选项来建立列表.

Don't use 100!!!-您可能不会希望将type=listargparse一起使用.永远不会.


LONG ANSWER

让我们更详细地看看人们可能try 的一些不同的方法,以及最终结果.

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)

以下是您可以预期的输出:

$ python arg.py --default 1234 2345 3456 4567
...
arg.py: error: unrecognized arguments: 2345 3456 4567

$ python arg.py --list-type 1234 2345 3456 4567
...
arg.py: error: unrecognized arguments: 2345 3456 4567

$ # Quotes won't help here... 
$ python arg.py --list-type "1234 2345 3456 4567"
['1', '2', '3', '4', ' ', '2', '3', '4', '5', ' ', '3', '4', '5', '6', ' ', '4', '5', '6', '7']

$ python arg.py --list-type-nargs 1234 2345 3456 4567
[['1', '2', '3', '4'], ['2', '3', '4', '5'], ['3', '4', '5', '6'], ['4', '5', '6', '7']]

$ python arg.py --nargs 1234 2345 3456 4567
['1234', '2345', '3456', '4567']

$ python arg.py --nargs-int-type 1234 2345 3456 4567
[1234, 2345, 3456, 4567]

$ # Negative numbers are handled perfectly fine out of the box.
$ python arg.py --nargs-int-type -1234 2345 -3456 4567
[-1234, 2345, -3456, 4567]

$ python arg.py --append-action 1234 --append-action 2345 --append-action 3456 --append-action 4567
['1234', '2345', '3456', '4567']

Takeaways:

  • Use nargs or action='append'
    • 从用户的Angular 来看,nargs可能更直接,但如果存在位置参数,它可能是不直观的,因为argparse无法分辨什么应该是位置参数,什么属于nargs;如果你有位置参数,那么action='append'可能是一个更好的 Select .
    • 仅当给予nargs'*''+''?'时,上述情况才成立.如果您提供一个整数(例如4),那么混合带有nargs和位置参数的选项将不会有问题,因为argparse将确切地知道该选项应该有多少个值.
  • 不要在命令行1
  • 不要使用type=list,因为它将返回列表列表
    • 之所以会发生这种情况,是因为在幕后argparse使用值type强制each individual given argument您 Select type,而不是所有参数的聚合.
    • 您可以使用type=int(或其他值)来获取整数(或其他值)的列表

1:我不是指一般情况..我的意思是用引号来表示pass a list to 100不是你想要的.

Python相关问答推荐

如何用symy更新分段函数

计算所有前面行(当前行)中列的值

Chatgpt API不断返回错误:404未能从API获取响应

GL pygame无法让缓冲区与vertextPointer和colorPointer一起可靠地工作

提取两行之间的标题的常规表达

点到面的Y距离

Deliveryter Notebook -无法在for循环中更新matplotlib情节(保留之前的情节),也无法使用动画子功能对情节进行动画

'discord.ext. commanders.cog没有属性监听器'

运行Python脚本时,用作命令行参数的SON文本

查找两极rame中组之间的所有差异

如何使Matplotlib标题以图形为中心,而图例框则以图形为中心

将pandas导出到CSV数据,但在此之前,将日期按最小到最大排序

用渐近模计算含符号的矩阵乘法

Pandas Data Wrangling/Dataframe Assignment

使用字典或列表的值组合

什么是一种快速而优雅的方式来转换一个包含一串重复的列,而不对同一个值多次运行转换,

如何获得满足掩码条件的第一行的索引?

如何在SQLAlchemy + Alembic中定义一个"Index()",在基表中的列上

Polars表达式无法访问中间列创建表达式

Pandas:将值从一列移动到适当的列