amphibient amphibient - 1 month ago 12
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

argparse
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


myScript.py --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
scrptVarClean=True
if
-clean
is provided and
False
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


pgCloner.py: error: argument -clean: expected one argument


How can I use an optional boolean argument with argparse?

Answer

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

parser.add_argument('-c', '--clean', action="store_true")