如何通过命令行将数组传递给python
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36926077/
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
How to pass an array to python through command line
提问by Luyao Wang
I am trying to pass an array to the python
我正在尝试将数组传递给 python
import sys
arr = sys.argv[1]
print(arr[2])
My command is
我的命令是
python3 test.py [1,2,3,4,5] 0
I hope the result it
希望结果吧
2
However, it is
然而,它是
,
回答by Barmar
The elements of argv
are strings, they're not parsed like literals in the program.
的元素argv
是字符串,它们不像程序中的文字那样被解析。
You should just pass a comma-separated string (without the brackets):
您应该只传递一个逗号分隔的字符串(不带括号):
python3 test.py 1,2,3,4,5 0
and then use split()
to convert it to an array.
然后使用split()
将其转换为数组。
import sys
arr = sys.argv[1].split(',')
print(arr[2])
回答by alexis
Commandline arguments are strings. Even integers have to be converted from string to int
. If you use the list syntax you show in your example, you'll need to run the argument through some sort of parser (your own parser, something from ast
, or eval
-- but don't use eval
). But there's a simpler way: Just write the arguments separately, and use a slice of sys.argv
as your list. Space-separated arguments is the standard way to pass multiple arguments to a commandline program (e.g., multiple filenames to less
, rm
, etc.).
命令行参数是字符串。甚至整数也必须从字符串转换为int
. 如果您使用示例中显示的列表语法,则需要通过某种解析器(您自己的解析器、来自ast
或eval
-- 但不要使用eval
)来运行参数。但是有一种更简单的方法:只需单独编写参数,并使用一个切片sys.argv
作为您的列表。空间分隔参数是将多个参数传递给一个命令行程序(例如,多个文件名到标准方式less
,rm
等)。
python3 test.py -n a b c 1 2 3
First you'd identify and skip arguments that have a different purpose (-n
in the above example), then simply keep the rest:
首先,您将识别并跳过具有不同目的的参数(-n
在上面的示例中),然后只需保留其余部分:
arr = sys.argv[2:]
print(arr[3]) # Prints "1"
PS. You also need to protect any argument from the shell, by quoting any characters with special meaning(*
, ;
, spaces that are part of an argument, etc.). But that's a separate issue.
附注。您还需要通过引用具有特殊含义的任何字符(*
、;
、作为参数一部分的空格等)来保护 shell 中的任何参数。但这是一个单独的问题。