The Python Oracle

argparse module How to add option without any argument?

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Hypnotic Orient Looping

--

Chapters
00:00 Argparse Module How To Add Option Without Any Argument?
00:59 Accepted Answer Score 339
01:14 Answer 2 Score 138
01:29 Thank you

--

Full question
https://stackoverflow.com/questions/5262...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #argparse

#avk47



ACCEPTED ANSWER

Score 339


As @Felix Kling suggested, to create an option that needs no value, use action='store_true', 'store_false' or 'store_const'. See documentation.

>>> 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



ANSWER 2

Score 138


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')