amphibient amphibient - 1 year ago 85
Python Question

argparse usage with options, not parameters

If I am passing an boolean option to my script, which is basically true if the option is supplied and false if not, how do I process it differently with

than a parameter that holds value.

For example, my script takes a parameter propFile, which holds a value and an option clean, which is just a true/false flag. The usage is --propFile=path/to/my/prop.file -clean

Note that I try to differentiate between parameters and options on the user level by assigning two dashes to the former and a single dash to the latter, which shouldn't matter to the interpreter.

I want to assign
is provided and
if not.

What I tried is:

argparser = argparse.ArgumentParser()
argparser.add_argument('--propFile', help='Properties file path')
argparser.add_argument('-clean', help='Clean?')
args = argparser.parse_args();
propFile = args.props
clean = args.clean

but I got error: argument -clean: expected one argument

How can I use an optional boolean argument with argparse?

Answer Source

Value of clean will be True if "--clean" or "-c" is supplied, else False

parser.add_argument('-c', '--clean', action="store_true")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download