The Python Oracle

argparse module How to add option without any argument?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Track title: CC M Beethoven - Piano Sonata No 3 in C 3

--

Chapters
00:00 Question
01:17 Accepted answer (Score 324)
01:35 Answer 2 (Score 130)
01:58 Thank you

--

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

Accepted answer links:
[@Felix Kling suggested]: https://stackoverflow.com/questions/5262...

Answer 2 links:
[action]: http://docs.python.org/dev/library/argpa...

--

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