r/pythonhelp • • Dec 01 '22

how to pass multiple flags in argparse?

I have these lines of code and im trying to pass something like ScriptName.py --naruto --goku
but its giving error of unexpected arguments. when I pass only one, for example only --naruto, then its working fine. any help on how to pass multiple flags in python?

parser.add_argument('--naruto', action='store_true')

parser.add_argument('--transformers', action='store_true')

parser.add_argument('--goku', action='store_true')

2 Upvotes

5 comments sorted by

1

u/Goobyalus Dec 01 '22

How exactly are you running the script, and what is the complete error output?

This works as expected:

from argparse import ArgumentParser

parser = ArgumentParser()

parser.add_argument("--naruto", action="store_true")
parser.add_argument("--transformers", action="store_true")
parser.add_argument("--goku", action="store_true")

args = parser.parse_args("--naruto --transformers".split())

print(args)

Output:

Namespace(goku=False, naruto=True, transformers=True)

so maybe you're invoking the script in a weird way.

1

u/[deleted] Dec 01 '22

im running the script like this
py scriptName.py --naruto --goku
my intention is that one flag is basically a yes or no thing and the other flag is a service that would be getting used. (naruto, goku etc names are random here).
based on the yes or no flag, the other service flag would get selected and the operation would get performed. maybe my code is not right for what I am trying to achieve. ?

1

u/Goobyalus Dec 01 '22

I'm not sure I follow -- what do you want as a result of parsing the arguments?

Are you parsing successfuly, and getting a namespace like what I pasted above? What's unexpected?

3

u/[deleted] Dec 01 '22

I am so sorry. It's my fault. you're right, I was debugging it wrong. I spent last 5 hours trying to figure this out.

for anyone experiencing the same issue, when you are debugging using a launch.json file. make sure your args are like this "args": [
"--naruto", "--goku"
],
I had set up args like this "--naruto --goku"

1

u/Goobyalus Dec 01 '22

No problem, glad you figured it out