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.