Dan
Dan

Reputation: 15

Accepting more arguments with argparse

I am writing a script using python and argparse:

import argparse

parser = prgparse.ArgumentParser(description="do a or b")
parser.add_argument("-a", "--funcA", help="do A")
parser.add_argument("-b", "--funcB", help="do B")

args = parser.parse_args()

if args.funcA:
    print(args.funcA)
if args.funcB:
    print(args.funcB)

I want to be able to run it with python3 parseab.py -a 11 -b 22 -a 33, and that funcA will be performed twice with 11 and 33, and funcB once with 22.

Right now each function is happening only once.

*I do not want to be able to accept more arguments after each option, but to be able to accept several instances of the same function.

Thank you!

Upvotes: 1

Views: 1014

Answers (1)

Filip Kubicz
Filip Kubicz

Reputation: 498

To be able to pass the same option multiple times to your script, you can use append action of argparse (as noted by @barny).

Then, you should take the list of values, and call function a() for every value of the list that you received from argparse.

Here's the code:

import argparse

parser = argparse.ArgumentParser()

# You must provide the flag once per input.
parser.add_argument('-a', '--funcA', help='do A', action='append')
parser.add_argument('-b', '--funcB', help='do B', action='append')

args = parser.parse_args()
if args.funcA:
    for elemA in args.funcA:
        print("a: ", elemA)
    for elemB in args.funcB:
        print("b :", elemB)

And the output:

python3 parseab.py -a 11 -b 22 -a 33
a:  11
a:  33
b : 22

Here is the answer that gives more details on other possibilities: How can I pass a list as a command-line argument with argparse?

Upvotes: 2

Related Questions