Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing argument values for argparse in Python

Tags:

python

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?

like image 450
Matt Hintzke Avatar asked Apr 14 '14 19:04

Matt Hintzke


1 Answers

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)
like image 98
msvalkon Avatar answered Sep 20 '22 15:09

msvalkon