If you are looking for a binary flag, then the argparse actions store_true or store_false provide exactly this. This approach is well explained in the accepted answer by @Jdog.
The official docs are also fairly clear. I would only complete the example with one line, so to make it very clear how the store_true/store_false act:
>>> parser = argparse.ArgumentParser() >>> parser.add_argument('--foo', action='store_true') >>> parser.add_argument('--fov', action='store_true') # this is not in the docs! >>> parser.add_argument('--bar', action='store_false') >>> parser.add_argument('--baz', action='store_false') >>> parser.parse_args('--foo --bar'.split()) # --baz and --fov are missing Out[4]: Namespace(bar=False, baz=True, foo=True, fov=False) # mind the fov=False
A slightly more powerful approach is to use the count action. You typically have used this type of flag already when setting the verbosity level when running a command.
For example ssh's verbose mode flag -v is a counter:
-v Verbose mode. Causes ssh to print debugging messages about its progress. This is helpful in debugging connection, authentication, and configuration problems. Multiple -v options increase the verbosity. The maximum is 3.
So if you run ssh it's non verbose, ssh -v is slightly verbose and ssh -vvv is maximally verbose.
With argparse in python such a counter flag can be defined as follows:
parser.add_argument('--verbose', '-v', action='count', default=0)
If you want to use it as a boolena (True/False) flag, then you need to cast args.verbose into a boolean. You can either do this explicitly yourself, or rely a conditional statement like if args.verbose: ....
Here is a full working example to illustrate how you can use the counter flag:
With the script test.py:
#!/usr/bin/env python3 # test.py import argparse parser = argparse.ArgumentParser() parser.add_argument('--verbose', '-v', action='count', default=0) args = parser.parse_args() if args.verbose: print('verbose') print(f'verbosity level: {args.verbose}') else: print('non-verbose')
You get the following outputs:
python test.py >> non-verbose
python test.py -v >> verbose >> verbosity level: 1
python test.py -vvv >> verbose >> verbosity level: 3