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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With