Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass an entire list as command line argument in Python?

Tags:

python

I was trying to pass two lists containing integers as arguments to a python code. But sys.argv[i] gets the parameters as a list of string.

Input would look like,

$ python filename.py [2,3,4,5] [1,2,3,4] 

I found the following hack to convert the list.

strA = sys.argv[1].replace('[', ' ').replace(']', ' ').replace(',', ' ').split() strB = sys.argv[2].replace('[', ' ').replace(']', ' ').replace(',', ' ').split() A = [float(i) for i in strA] B = [float (i) for i in strB] 

Is there a better way to do this?

like image 259
yogesh Avatar asked Sep 24 '15 12:09

yogesh


People also ask

Can I pass a list as an argument Python?

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.

Can you pass a list to * args?

yes, using *arg passing args to a function will make python unpack the values in arg and pass it to the function.

What list in Python contains arguments passed to a script?

The sys module exposes an array named argv that includes the following: argv[0] contains the name of the current Python program. argv[1:] , the rest of the list, contains any and all Python command line arguments passed to the program.


1 Answers

Don't reinvent the wheel. Use the argparse module, be explicit and pass in actual lists of parameters

import argparse # defined command line options # this also generates --help and error handling CLI=argparse.ArgumentParser() CLI.add_argument(   "--lista",  # name on the CLI - drop the `--` for positional/required parameters   nargs="*",  # 0 or more values expected => creates a list   type=int,   default=[1, 2, 3],  # default if nothing is provided ) CLI.add_argument(   "--listb",   nargs="*",   type=float,  # any type/callable can be used here   default=[], )  # parse the command line args = CLI.parse_args() # access CLI options print("lista: %r" % args.lista) print("listb: %r" % args.listb) 

You can then call it using

$ python my_app.py --listb 5 6 7 8 --lista  1 2 3 4 lista: [1, 2, 3, 4] listb: [5.0, 6.0, 7.0, 8.0] 
like image 164
MisterMiyagi Avatar answered Sep 21 '22 12:09

MisterMiyagi