To add an optional argument, simply omit the required parameter in add_argument() . args = parser. parse_args()if args.
The argparse module provides a convenient interface to handle command-line arguments. It displays the generic usage of the program, help, and errors. The parse_args() function of the ArgumentParser class parses arguments and adds value as an attribute dest of the object.
As @Felix Kling suggested use action='store_true'
:
>>> from argparse import ArgumentParser
>>> p = ArgumentParser()
>>> _ = p.add_argument('-f', '--foo', action='store_true')
>>> args = p.parse_args()
>>> args.foo
False
>>> args = p.parse_args(['-f'])
>>> args.foo
True
To create an option that needs no value, set the action
[docs] of it to 'store_const'
, 'store_true'
or 'store_false'
.
Example:
parser.add_argument('-s', '--simulate', action='store_true')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With