Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set value to variable in argparse if option passed in

Tags:

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.

like image 496
rodee Avatar asked Jun 18 '19 19:06

rodee


People also ask

How do you make an argument optional in Argparse?

To add an optional argument, simply omit the required parameter in add_argument() . args = parser. parse_args()if args.

What is Argparse ArgumentParser ()?

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.

What does Nargs do in Argparse?

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.


1 Answers

parser.add_argument('-y', '--y-option', action='store_const', const='enable_y', default='')

https://docs.python.org/3/library/argparse.html#action

like image 126
ohlr Avatar answered Sep 20 '22 22:09

ohlr