blazerix
blazerix

Reputation: 860

Python 2.7 Argparse Optional and Required arguments

So I've been frantically reading tutorials on argparse everywhere but can't seem to figure out why my program is getting an error. My code currently looks like this:

parser = argparse.ArgumentParser()
parser.add_argument("-d", "-debug", required = False, help = "optional parameter")
parser.add_argument("input_file", help = "file to be parsed")
args = parser.parse_args()

When I run my program with the command "python myprogram.py -d inputfile" it complains that there are too few arguments. Furthermore, when I just run it with inputfile as the parameter, it works.

Does anyone know why this might be happening?

Upvotes: 0

Views: 664

Answers (1)

mgilson
mgilson

Reputation: 309929

The default action for an argument is 'store'. store actions generally expect a value to be associated with the flag.

It looks like you want this to be a boolean switch type of flag in which case you want the 'store_true' action

parser = argparse.ArgumentParser()
parser.add_argument("-d", "--debug", required = False, help = "optional parameter", action = "store_true")
parser.add_argument("input_file", help = "file to be parsed")
args = parser.parse_args()

Upvotes: 3

Related Questions