如何在 Python 中将整个列表作为命令行参数传递?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32761999/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 12:12:40  来源:igfitidea点击:

How to pass an entire list as command line argument in Python?

python

提问by yogesh

I was trying to pass two lists containing integers as arguments to a python code. But sys.argv[i]gets the parameters as a list of string.

我试图将两个包含整数的列表作为参数传递给 python 代码。但是sys.argv[i]将参数作为字符串列表获取。

Input would look like,

输入看起来像,

$ python filename.py [2,3,4,5] [1,2,3,4]

I found the following hack to convert the list.

我发现以下技巧可以转换列表。

strA = sys.argv[1].replace('[', ' ').replace(']', ' ').replace(',', ' ').split()
strB = sys.argv[2].replace('[', ' ').replace(']', ' ').replace(',', ' ').split()
A = [float(i) for i in strA]
B = [float (i) for i in strB]

Is there a better way to do this?

有一个更好的方法吗?

采纳答案by Josh J

Command line arguments are always passed as strings. You will need to parse them into your required data type yourself.

命令行参数始终作为字符串传递。您需要自己将它们解析为所需的数据类型。

>>> input = "[2,3,4,5]"
>>> map(float, input.strip('[]').split(','))
[2.0, 3.0, 4.0, 5.0]
>>> A = map(float, input.strip('[]').split(','))
>>> print(A, type(A))
([2.0, 3.0, 4.0, 5.0], <type 'list'>)

Their are libraries like argparseand clickthat let you define your own argument type conversion but argparsetreats "[2,3,4]"the same as [2,3,4]so I doubt it will be useful.

它们是像argparseclick这样的库,可以让您定义自己的参数类型转换,但argparse处理方式"[2,3,4]"相同,[2,3,4]因此我怀疑它是否有用。

edit Jan 2019This answer seems to get a bit of action still so I'll add another option taken directly from the argparse docs.

编辑 2019 年 1 月这个答案似乎仍然有一些作用,所以我将添加另一个直接从 argparse 文档中获取的选项。

You can use action=appendto allow repeated arguments to be collected into a single list.

您可以使用action=append允许将重复的参数收集到一个列表中。

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action='append')
>>> parser.parse_args('--foo 1 --foo 2'.split())
Namespace(foo=['1', '2'])

In this case you would pass --foo ?once for each list item. Using OPs example: python filename.py --foo 2 --foo 3 --foo 4 --foo 5would result in foo=[2,3,4,5]

在这种情况下,您将为--foo ?每个列表项传递一次。使用 OP 示例:python filename.py --foo 2 --foo 3 --foo 4 --foo 5将导致foo=[2,3,4,5]

回答by Ilya Peterov

No, there is no way pass a list in a command line argument. Command line arguments are always string. But there is a better way to convert it to list. You can do it like that:

不,无法在命令行参数中传递列表。命令行参数始终是字符串。但是有一种更好的方法可以将其转换为列表。你可以这样做:

import ast

A = ast.literal_eval(strA)
B = ast.literal_eval(strB)

回答by idjaw

I tested this on my end, and my input looks like this:

我对此进行了测试,我的输入如下所示:

python foo.py "[1,2,3,4]" "[5,6,7,8,9]"

I'm doing the following to convert the two params of interest:

我正在执行以下操作来转换感兴趣的两个参数:

import ast
import sys

list1 = ast.literal_eval(sys.argv[1])
list2 = ast.literal_eval(sys.argv[2])

回答by pregmatch

You have to escape:

你必须逃脱:

python some.py \[2,3,4,5\] \[1,2,3,4\]

some.py

一些.py

import sys

print sys.argv[1]
print sys.argv[2]

this gives me:

这给了我:

[2,3,4,5]
[1,2,3,4]

Bash out

猛击

UPDATE:

更新

import sys
import ast

d = ast.literal_eval(sys.argv[1])
b = ast.literal_eval(sys.argv[2])

for a in d:
    print a

for e in b:
    print e

first will give:

首先会给:

2
3
4
5

and second will give

第二个会给

1
2
3
4

回答by postelrich

Why not:

为什么不:

python foo.py 1,2,3,4 5,6,7,8  

Much cleaner than trying to eval python and doesn't require your user to know python format.

比尝试 eval python 更干净,并且不需要您的用户知道 python 格式。

import sys

list1 = sys.argv[1].split(',')
list2 = [int(c) for c in sys.argv[2].split(',')]  # if you want ints

回答by MisterMiyagi

Don't reinvent the wheel. Use the argparse module, be explicit and pass in actual lists of parameters

不要重新发明轮子。使用argparse 模块,明确并传入实际的参数列表

import argparse
# defined command line options
# this also generates --help and error handling
CLI=argparse.ArgumentParser()
CLI.add_argument(
  "--lista",  # name on the CLI - drop the `--` for positional/required parameters
  nargs="*",  # 0 or more values expected => creates a list
  type=int,
  default=[1, 2, 3],  # default if nothing is provided
)
CLI.add_argument(
  "--listb",
  nargs="*",
  type=float,  # any type/callable can be used here
  default=[],
)

# parse the command line
args = CLI.parse_args()
# access CLI options
print("lista: %r" % args.lista)
print("listb: %r" % args.listb)

You can then call it using

然后你可以调用它使用

$ python my_app.py --listb 5 6 7 8 --lista  1 2 3 4
lista: [1, 2, 3, 4]
listb: [5.0, 6.0, 7.0, 8.0]

回答by akazuko

You can also do the following:

您还可以执行以下操作:

say, you have foo.py:

说,你有foo.py

import json
import sys
data = json.loads(sys.argv[1])
print data, type(data)

Then if you run the above as : python foo.py "[1,2,3]"

然后,如果您将上述内容运行为: python foo.py "[1,2,3]"

Output:

输出:

[1, 2, 3] <type 'list'>

[1, 2, 3] <type 'list'>