Juha-Matti Santala
Community Builder. Dreamer. Adventurer.

Parse command line arguments with argparse

Batteries included is a blog series about the Python Standard Library. Each day, I share insights, ideas and examples for different parts of the library. Blaugust is an annual blogging festival in August where the goal is to write a blog post every day of the month.

Writing your own command line scripts and tools is one of the great joys of knowing how to program. I wrote about some of mine last month for IndieWeb Carnival as well as sharing my reasons for why I love them a few years ago.

Python comes with argparse module that allows you to declare your arguments, their types and options.

I wanted to bring this to the attention of my readers who might have not used it before but since I’ve already written about it at length, I’m gonna refer you to read that original piece How to parse command line arguments in Python.

Back when I wrote the original blog post, my main motivation was that I found its documentation a bit challenging to follow and wanted to document it again for myself as I found myself using it regularly:

argparse is a purpose-built tool for describing arguments declaratively. It packs a lot of base functionality behind a clean interface.

While the module itself has a clean interface, I find its documentation a bit difficult to follow. Every time I end up building command line tools with Python, I have to read through a bunch of blog posts and Stack Overflow posts to get to where I want to go.