I am trying to set up some simple flag arguments for my program but cannot figure out how to access them. I have the argparser:
parser = argparse.ArgumentParser(description='Simple PostScript Interpreter')
parser.add_argument('-s', action="store_true")
parser.add_argument('-d', action="store_true")
parser.parse_args(sys.argv[1:])
The program should take either sps.py -s, sps.py -d, or sps.py on the command line. Then I just want to check whether or not the -s flag was set or the -d flag was set. If neither were set, then just default to -d.
What do I need to do to access the boolean values that are set by the parser?
3 Answers 3
You don't need to give parse_args() any parameters. You call it like this:
>>> args = parser.parse_args()
which will return a NameSpace object. You can access your arguments using the dot notation:
>>> args.s
False
>>> args.d
False
Working example:
import argparse
parser = argparse.ArgumentParser(description='Simple PostScript Interpreter')
parser.add_argument('-s', action="store_true")
parser.add_argument('-d', action="store_true")
args = parser.parse_args()
print args
Running it like so:
msvalkon@Lunkwill:/tmp$ python sps.py
Namespace(d=False, s=False)
msvalkon@Lunkwill:/tmp$ python sps.py -d
Namespace(d=True, s=False)
msvalkon@Lunkwill:/tmp$ python sps.py -s
Namespace(d=False, s=True)
5 Comments
sps.py -d it says error: unrecognized arguments: -dpython sps.py -d or -s works fine for me with your code, when I remove the sys.argv[1:] from parse_args(). How exactly are you running this?sys.argv[1:] which would've resulted in weird option values. You do need to have the add_argument() for any command line argument you wish to implement. Perhaps I should've talked about function arguments, or parameters instead of just arguments to avoid confusion.Try adding this:
args = parser.parse_args()
print args.s
print args.d
Comments
Your existing code is mostly correct:
parser = argparse.ArgumentParser(description='Simple PostScript Interpreter')
parser.add_argument('-s', action="store_true")
parser.add_argument('-d', action="store_true")
args = parser.parse_args()
although the default argument to parse_args makes passing sys.argv[1:] unnecessary. Since each argument is parsed independently, you'll need a post-processing step after the arguments are parsed:
if not args.s and not args.d:
args.s = True