I am trying to pass an array to the 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
,
I am trying to pass an array to the 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
,
The elements of argv
are strings, they're not parsed like literals in the program.
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.
import sys
arr = sys.argv[1].split(',')
print(arr[2])
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.).
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:
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.