将列表作为命令行参数传递

将列表作为命令行参数传递

本文介绍了如何使用 argparse 将列表作为命令行参数传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to pass a list as an argument to a command line program. Is there an argparse option to pass a list as option?

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' 设置(取决于您希望用户界面的行为方式).

SHORT ANSWER

Use the nargs option or the 'append' setting of the action option (depending on how you want the user interface to behave).

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

nargs='+' takes 1 or more arguments, nargs='*' takes zero or more.

追加

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

With append you provide the option multiple times to build up the list.

不要使用 type=list!!! - 可能没有您想要将 type=listargparse.曾经.

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

Let's take a look in more detail at some of the different ways one might try to do this, and the end result.

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)

这是您可以预期的输出:

Here is the output you can expect:

$ 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 会准确地知道该选项需要多少个值.
    • Use nargs or action='append'
      • nargs can be more straightforward from a user perspective, but it can be unintuitive if there are positional arguments because argparse can't tell what should be a positional argument and what belongs to the nargs; if you have positional arguments then action='append' may end up being a better choice.
      • The above is only true if nargs is given '*', '+', or '?'. If you provide an integer number (such as 4) then there will be no problem mixing options with nargs and positional arguments because argparse will know exactly how many values to expect for the option.
      • 发生这种情况是因为在幕后argparse 使用type 的值来强制每个给定的参数你选择的type,不是所有参数的总和.
      • 您可以使用 type=int(或其他)来获取整数列表(或其他)
      • This happens because under the hood argparse uses the value of type to coerce each individual given argument you your chosen type, not the aggregate of all arguments.
      • You can use type=int (or whatever) to get a list of ints (or whatever)

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

      : I don't mean in general.. I mean using quotes to pass a list to argparse is not what you want.

      这篇关于如何使用 argparse 将列表作为命令行参数传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 13:03