如何使用 argparse 将列表作为命令行参数传递?

新手上路,请多包涵

我正在尝试将列表作为参数传递给命令行程序。是否有 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"

原文由 carte blanche 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.4k
2 个回答

简短的回答

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

纳尔格斯

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='*' 接受零个或多个。

附加

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 您可以多次提供该选项来构建列表。

不要使用 type=list !!! - 可能没有您想将 type=listargparse 18c53151f3862a07c726dbdc8d34f— 一起使用的情况。曾经。


长答案

让我们更详细地了解一些可能尝试执行此操作的不同方式以及最终结果。

 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']

_要点_:

  • 使用 nargsaction='append'
    • nargs 从用户的角度来看可能更直接,但如果有位置参数可能不直观,因为 argparse 无法分辨什么应该是位置参数以及什么属于 nargs ;如果您有位置参数,那么 action='append' 可能最终成为更好的选择。
    • 仅当给出 '*' nargs '+''?' 如果您提供一个整数(例如 4 ),那么将选项与 nargs 和位置参数混合使用不会有问题,因为 argparse 将确切知道有多少值期望选项。
  • 不要在命令行上使用引号1
  • 不要使用 type=list ,因为它会返回一个列表列表
    • 发生这种情况是因为 argparse 使用 type 的值来强制 每个给定的参数 你选择的 type ,而不是所有参数的总和。
    • 您可以使用 type=int (或其他)来获取整数列表(或其他)

1 :我不是说一般……我的意思是使用引号 将列表传递给 argparse 不是你想要的。

原文由 SethMMorton 发布,翻译遵循 CC BY-SA 4.0 许可协议

我更喜欢传递一个分隔字符串,我稍后会在脚本中对其进行解析。这样做的原因是;该列表可以是任何类型 intstr ,有时使用 nargs 如果有多个可选参数,我会遇到问题

parser = ArgumentParser()
parser.add_argument('-l', '--list', help='delimited list input', type=str)
args = parser.parse_args()
my_list = [int(item) for item in args.list.split(',')]

然后,

 python test.py -l "265340,268738,270774,270817" [other arguments]

要么,

 python test.py -l 265340,268738,270774,270817 [other arguments]

会工作正常。分隔符也可以是一个空格,但它会像问题示例中那样在参数值周围强制加引号。

或者您可以使用 Chepner 评论中建议的 lambda 类型:

 parser.add_argument('-l', '--list', help='delimited list input',
    type=lambda s: [int(item) for item in s.split(',')])

原文由 dojuba 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题