Python: argparse action store
spO0q
Posted on June 10, 2023
As we already saw in this series, argparse
is a built-in Python module that can help you build friendly CLI tools:
It's quite straightforward, but some parts, like actions, may be confusing for beginners.
Create on/off flags
It's not uncommon to need some on/off flag in our CLI commands:
import argparse
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="My client")
parser.add_argument('-v', '--verbose', action='store_true')
The action parameter allows setting how arguments should be handled:
'store', 'store_const', 'store_true', 'append', 'append_const', 'count', 'help', 'version'
It might seem self-explanatory, but you might struggle to understand how to use values like store_true
.
Don't be confused. store_true
will default to False
. If you need to set a default value to True
, use store_false
instead.
Create arbitrary actions
If you need something like --exec
/ --no-exec
, you can leverage BooleanOptionalAction
(Python 3.9):
parser.add_argument('--exec', action=argparse.BooleanOptionalAction)
Posted on June 10, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 12, 2024