1

I need some help regarding using argparse. What I want to achieve is that I need to pass in only one argument, it could be one of the followings: --k, --r, --b, --p,(ignore the rest). If the argument count is not 1, print "usage" information and quit. Also the program needs to know which flag is passed in in order to create corresponding object. I tried several times but I doesn't work, can anyone give me a hint on this? Thanks.

asked Dec 10, 2011 at 22:57
1
  • 3
    "I tried several times but I doesn't work": Can you post what you tried and explain what exactly doesn't work? Commented Dec 10, 2011 at 22:59

2 Answers 2

4

What you need to use to accomplish that is a mutually exclusive group:

import argparse
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()
group.add_argument('-k', action='store_true')
group.add_argument('-r', action='store_true')
group.add_argument('-b', action='store_true')
group.add_argument('-p', action='store_true')
parser.parse_args()

As it can be seen in the example below, only one option in a mutually exclusive group is allowed at the same time:

$ python test.py -k -r -b -p
usage: test.py [-h] [-k | -r | -b | -p]
test.py: error: argument -r: not allowed with argument -k

To check which flag was passed, you just need to look at the argparse.Namespace object returned by parse_args method (the flag passed will be set to True).

answered Dec 10, 2011 at 23:12

1 Comment

Good job! It seems that I'm totally on the wrong track, thx for the sample!
3

How about not using argparse at all? It doesn't seem really necessary.

if len(sys.argv) != 2:
 print_usage()
arg = sys.argv[1]
if arg not in ["--k", "--r", "--b", "--p"]:
 print_usage()
# Do whatever you want with arg
answered Dec 10, 2011 at 23:01

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.