skidjoe
skidjoe

Reputation: 649

How to set an argparse argument to a value if it's included in the CLI otherwise set it to another value?

I have an argument that I wish to set to a value if the flag is included in the CLI, otherwise I want it to be set to another. Is there a way to do this with argparse?

The way I do this using sys.argv is the following:

main("first_val" if "-t" in sys.argv else "second_val")

How would I do this with argparse?

Upvotes: 0

Views: 20

Answers (1)

larsks
larsks

Reputation: 312038

You can use the store_true action if you want a boolean value:

p.add_argument('-t', action='store_true')

The value of the t option will be True if its passed on the command line, None otherwise.

If you want specific values, you can combine store_const and default:

p.add_argument('-t', action='store_const', const='foo', default='bar')

The value of t will be foo if -t was passed on the command line, bar otherwise.

Upvotes: 1

Related Questions