Python argparse command line flags without arguments
Solution 1:
As you have it, the argument w
is expecting a value after -w
on the command line. If you are just looking to flip a switch by setting a variable True
or False
, have a look here (specifically store_true and store_false)
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-w', action='store_true')
where action='store_true'
implies default=False
.
Conversely, you could haveaction='store_false'
, which implies default=True
.
Solution 2:
Adding a quick snippet to have it ready to execute:
Source: myparser.py
import argparse
parser = argparse.ArgumentParser(description="Flip a switch by setting a flag")
parser.add_argument('-w', action='store_true')
args = parser.parse_args()
print args.w
Usage:
python myparser.py -w
>> True