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.
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.
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
Videos
Using argparse, how do you add a flag that doesn't require an argument, but can optionally take an argument.
Desired behaviour
$ keychart -c # outputs a csv to wherever PWD the script is runing from $ keychart -c /home/nick/csv # outputs a csv to specified directory
At present, my code that (almost) does what I want, but won't handle being given an argument:
# 'scratch.py'
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-c", "--csv", help="write results to a csv to disk", action='store_true')
print(args.csv)
# works as desired
$ python3 scratch.py -c
True
# doesn't work as desired
$ python3 scratch.py -c testo
usage: scratch.py [-h] [-c]
scratch.py: error: unrecognized arguments: testo