2

I know that we can use sys.argv, but I am having an issue with this.

I want to pass a list as an argument :

Example [5,1,6,[5,2]] 

This is a nested list and I want to take it as input the way it is.

python myprogram.py [5,1,6,[5,2]] 

This is my program:

import sys;


input_list = sys.argv[1].split(',')
print(input_list)

I did obtain the list, however if I output it, it is completely wrong structurally:

['[5', '1', '6', '[5', '2]]']

As you can see, instead of input_list[0] == 5 , I have it equal to '[5', also the nested list that I inputted now is no more nested. Instead of input_list[3] ==[5,2], input_list[3] is equal to '[5'.

What should I do? I need to take the list as it is in order to work with it.

Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59
mana lamo
  • 41
  • 5
  • You *could* `eval()` it, but I'd rather suggest you look at the `argparse` module to see if that can help you. – brunns May 08 '19 at 11:35

1 Answers1

2

Try this:

import ast

input_list = ast.literal_eval(sys.argv[1])

then the output will be

[5, 1, 6, [5, 2]]
Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59