如何在 Python 中将整个列表作为命令行参数传递? [英] How to pass an entire list as command line argument in Python?

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

问题描述

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

输入看起来像,

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

我发现了以下转换列表的技巧.

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]

有没有更好的方法来做到这一点?

解决方案

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

<预><代码>>>>输入 = [2,3,4,5]">>>地图(浮动,input.strip('[]').split(','))[2.0, 3.0, 4.0, 5.0]>>>A = map(float, input.strip('[]').split(','))>>>打印(A,类型(A))([2.0, 3.0, 4.0, 5.0], )

有像 argparseclick 允许您定义自己的参数类型转换,但 argparse 处理 "[2,3,4]"[ 2 , 3 ,4 ] 所以我怀疑它会有用.

edit Jan 2019 这个答案似乎仍然有一些作用,所以我将添加另一个直接取自 argparse 文档的选项.

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

<预><代码>>>>解析器 = argparse.ArgumentParser()>>>parser.add_argument('--foo', action='append')>>>parser.parse_args('--foo 1 --foo 2'.split())命名空间(foo=['1', '2'])

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

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.

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?

解决方案

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

There are libraries like argparse and click that let you define your own argument type conversion but argparse treats "[2,3,4]" the same as [ 2 , 3 , 4 ] so I doubt it will be useful.

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

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

>>> 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 5 would result in foo=[2,3,4,5]

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆