blazerix blazerix - 2 months ago 10
Python Question

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?

Answer

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()
Comments