tags:

views:

97

answers:

2

I am using getopt to process a command line optional argument, which should accept a list. Something like this:

foo.py --my_list=[1, 2, 3, 4,5] 

But this trims everything after "[1,"

My questions are: A) Is there a way to specify a list without converting it into a string? (using getopt)

B) If I am to convert the list into a string, how to convert this list to a string? e.g. something like mylist.split("?") to get rid of square brackets ?? is there a better way?

Thank you

+4  A: 

Maybe you should just enclose the argument in quotes?

foo.py "--my_list=[1, 2, 3, 4,5]"

Otherwise every space will be treated as a separator for arguments.

Joey
And that's not because of python but due to the shell which parses the arguments and provides them to the python program.
extraneon
Partly true. On Windows the command line is just a string. And even UNIX does not have any special data structure that passes arguments to the program, it's still only a string. However, it's a widely implemented convention, but not universal. And yes, the C runtime has specifications for that.
Joey
You can also do `--my-list="[1, 2, 3, 4,5]"`. I usually use this form because it's usually something like `--my-list="$MY_LIST"`.
Mike DeSimone
Ah, I thought so much already but wasn't familiar enough with getopt to know whether that would work.
Joey
+4  A: 

There are two options that I can think of:

  • Use optparse, and use append action to specify what you want to do as: foo.py --my_list=1 --my_list=2 ....
  • Specify your commandline as foo.py --my_list='1,2,3,4,5', and then use x.split(',') to get your values in a list. You can use getopt or optparse for this method.

The advantage of the first method is that you can get integer values in the list directly, at the expense of the commandline being longer (but you can add a single-charecter option for --my_list if you want). The advantage of the second is shorter command line, but after the split(), you need to convert the string values '1', '2', etc., to integers (pretty easy as well).

Alok