8

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="")

2 Answers 2

15

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).

Sign up to request clarification or add additional context in comments.

2 Comments

perfect thank you, if i add nargs, i juste have to make action='store' and it works like a charm
@CondaKan store is the default action, you don't have to specify it explicitly
1

Being aware, you asked for argparse solution, I would like to present alternative solution using package docopt

Install it first:

$ pip install docopt

Write the code:

"""Usage:
    main.py -a <arg>...
"""

if __name__ == "__main__":
    from docopt import docopt
    resargs = docopt(__doc__)
    print resargs

Run it to show usage instrucitons:

$ python main.py
Usage:
    main.py -a <arg>...

Call it with your parameters:

$ python main.py -a AA BB CC
{'-a': True,
 '<arg>': ['AA', 'BB', 'CC']}

Btw. if you do not need the -a option, you shall directly allow passing the arguments. It makes usage simpler to the user.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.