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
You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function.
argv is the list of command-line arguments. len(sys. argv) is the number of command-line arguments.
Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.
If so, you'll need to use the input() command. The input() command allows you to require a user to enter a string or number while a program is running. The input() method replaced the old raw_input() method that existed in Python v2. Open a terminal and run the python command to access Python.
There are two options that I can think of:
append
action to specify what you want to do as: foo.py --my_list=1 --my_list=2 ...
.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).
If I can't use a standard parser (optparse or argparse) to my application then I use the ast.literal_eval function to parse input arguments of type list as follows:
import sys, ast inputList = ast.literal_eval( sys.argv[1] ) print type( inputList ) print inputList
Let suppose that this code is stored in testParser.py file. By executing the script:
$ python testParser.py "[1,2,3,4, [123, 456, 789], 'asdasd']"
we get the following output:
<type 'list'> [1, 2, 3, 4, [123, 456, 789], 'asdasd']
So, using the secure enough ast.literal_eval function and inserting the list as a string of code we have the desirable result.
Useful links:
Using python's eval() vs. ast.literal_eval()?
http://docs.python.org/2/library/functions.html?highlight=eval#eval
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With