Matt Hintzke
Matt Hintzke

Reputation: 7984

Accessing argument values for argparse in 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?

Upvotes: 23

Views: 24701

Answers (3)

chepner
chepner

Reputation: 530960

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

Upvotes: 0

msvalkon
msvalkon

Reputation: 12077

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)

Upvotes: 25

drez90
drez90

Reputation: 814

Try adding this:

args = parser.parse_args()
print args.s
print args.d

Upvotes: 4

Related Questions