Python Argparse by Example
Build flexible scripts with command line arguments
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.
Basic usage
There are four basic steps to using argparse
in your code:
- import the
argparse
module; - create the parser;
- add arguments;
- 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]…