import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-y', '--y-option', action='store_true')
args = parser.parse_args()
y_option = "enable_y" if args.y_option else ''
print(y_option)
if -y
or --y-option
is passed in, I want to set variable y_option
to enable_y
else an empty string, I believe this should be possible with argparse so the y_option = ...
line is not needed? I couldn't figure it out. I cannot use default as it will set default value even if -y
is not passed in.
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.
The add_argument() method action - The basic type of action to be taken when this argument is encountered at the command line. nargs - The number of command-line arguments that should be consumed. const - A constant value required by some action and nargs selections.
parser.add_argument('-y', '--y-option', action='store_const', const='enable_y', default='')
https://docs.python.org/3/library/argparse.html#action
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