Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List of arguments with argparse

I'm trying to pass a list of arguments with argparse but the only way that I've found involves rewriting the option for each argument that I want to pass:

What I currently use:

main.py -t arg1 -a arg2

and I would like:

main.py -t arg1 arg2 ...

Here is my code:

parser.add_argument("-t", action='append', dest='table', default=[], help="")
like image 317
CondaKan Avatar asked May 06 '14 08:05

CondaKan


People also ask

How do you pass multiple arguments with Argparse in Python?

Multiple Input Arguments Using the nargs parameter in add_argument() , you can specify the number (or arbitrary number) of inputs the argument should expect. In this example named sum.py , the --value argument takes in 3 integers and will print the sum.

How do you pass arguments in Argparse?

All parameters should be passed as keyword arguments. Each parameter has its own more detailed description below, but in short they are: prog - The name of the program (default: os.path.basename(sys.argv[0]) ) usage - The string describing the program usage (default: generated from arguments added to parser)

What does Argparse parse_args return?

The return value from parse_args() is a Namespace containing the arguments to the command. The object holds the argument values as attributes, so if your argument dest is "myoption", you access the value as args.


1 Answers

Use nargs:

ArgumentParser objects usually associate a single command-line argument with a single action to be taken. The nargs keyword argument associates a different number of command-line arguments with a single action.

For example, if nargs is set to '+'

Just like '*', all command-line args present are gathered into a list. Additionally, an error message will be generated if there wasn’t at least one command-line argument present.

So, your code would look like

parser.add_argument('-t', dest='table', help='', nargs='+')

That way -t arguments will be gathered into list automatically (you don't have to explicitly specify the action).

like image 80
vaultah Avatar answered Oct 03 '22 13:10

vaultah