DEV Community

spO0q
spO0q

Posted on

2

Python: argparse action store

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')
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay