Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass an array to python through command line [duplicate]

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

,
like image 528
Luyao Wang Avatar asked Apr 28 '16 21:04

Luyao Wang


People also ask

How do you duplicate an array in Python?

To create a deep copy of an array in Python, use the array. copy() method. The array. copy() method does not take any argument because it is called on the original array and returns the deep copied array.

How do you pass an array as a command line argument in Python?

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.). PS.

How do you pass an integer array in Python?

Give the list as user input using the list(),map(),split(),int functions and store it in a variable. Pass 'i', above given list as arguments to the array() function to create an array. Store it in another variable. Here 'i' indicates the datatype of the given array elements is integer.


1 Answers

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])
like image 65
Barmar Avatar answered Oct 08 '22 13:10

Barmar