Python Argparse by Example

Build flexible scripts with command line arguments

Rupert Thomas
The Startup

--

The argparse module is part of the Python standard library, and lets your code accept command line arguments. This makes your code easy to configure at run-time. There are multiple ways to do this in Python, but argparse is the most powerful with minimal additional code required. This article is a collection of example code snippets — I wrote it because the official documentation is quite heavy-going, and couldn’t find a suitable quick reference.

Simpsons — 20th Century Fox

Basic usage

There are four basic steps to using argparse in your code:

  1. import the argparse module;
  2. create the parser;
  3. add arguments;
  4. parse the arguments.

This adds a single positional, mandatory (required) argument. If we run our script but forget to add the argument, we will get an error. If we supply an argument, it gets printed to the console:

$ python argparse_basic.py
usage: argparse_basic.py [-h]…

--

--

Rupert Thomas
The Startup

Technology consultant from Cambridge, UK specialising in software engineering, machine learning, machine vision, and building data-driven products