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

2024-04-20 12:44:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图将列表作为参数传递给命令行程序。是否有^{}选项将列表作为选项传递?

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"

Tags: store命令行程序addparser列表type选项
3条回答

TL;DR

使用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='+'接受一个或多个参数,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一起使用。永远。


让我们更详细地了解一下人们可能尝试的一些不同方法,以及最终的结果。

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,因为它将返回列表列表
    • 之所以会发生这种情况,是因为在hood下argparse使用type的值来强制每个给定的参数您选择的type,而不是所有参数的集合。
    • 您可以使用type=int(或其他)来获取int列表(或其他)

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

除了^{}之外,如果事先知道列表,您可能还需要使用^{}

>>> parser = argparse.ArgumentParser(prog='game.py')
>>> parser.add_argument('move', choices=['rock', 'paper', 'scissors'])
>>> parser.parse_args(['rock'])
Namespace(move='rock')
>>> parser.parse_args(['fire'])
usage: game.py [-h] {rock,paper,scissors}
game.py: error: argument move: invalid choice: 'fire' (choose from 'rock',
'paper', 'scissors')

我更喜欢传递一个分隔字符串,稍后在脚本中解析它。原因是:列表可以是任何类型的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]

会起作用的。分隔符也可以是一个空格,尽管它会像在问题的示例中那样在参数值周围强制使用引号。

相关问题 更多 >