Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a tuple as command line argument

My requirement is to pass a tuple as command line argument like

--data (1,2,3,4) 

I tried to use the argparse module, but if I pass like this it is receiving as the string '(1,2,3,4)'. I tried by giving type=tuple for argparse.add_argument, but is of no use here.

Do I have to add a new type class and pass that to type argument of add_argument?

Update

I tried the ast.literal_eval based on answers. Thanks for that. But it is giving spaces in the result as shown below.

(1,2,3,4) <type 'str'> (1, 2, 3, 4) <type 'tuple'> 
like image 314
user1423015 Avatar asked Nov 06 '15 10:11

user1423015


People also ask

How do you pass a tuple as an argument?

This method of passing a tuple as an argument to a function involves unpacking method. Unpacking in Python uses *args syntax. As functions can take an arbitrary number of arguments, we use the unpacking operator * to unpack the single argument into multiple arguments.

Why is * args a tuple?

The *args thing returns tuple because of that, and if you really need a list, you can transform it with one line of code! So in general: It speeds up your program execution. You do not it to change the arguments. It is not that hard to change it's type.

Can we pass list as command line argument in Python?

The arguments that are given after the name of the program in the command line shell of the operating system are known as Command Line Arguments. Python provides various ways of dealing with these types of arguments. One of them is sys module.


1 Answers

Set nargs of the data argument to nargs="+" (meaning one or more) and type to int, you can then set the arguments like this on the command line:

--data 1 2 3 4 

args.data will now be a list of [1, 2, 3, 4].

If you must have a tuple, you can do:

my_tuple = tuple(args.data) 

Putting it all together:

parser = argparse.ArgumentParser() parser.add_argument('--data', nargs='+', type=int) args = parser.parse_args() my_tuple = tuple(args.data) 
like image 160
Alastair McCormack Avatar answered Sep 24 '22 01:09

Alastair McCormack