Parsing Command-Line Arguments In Python
This tutorial uses the built-in Pyton module
Complex command-line programs can be simplified with the concept of
sub-commands. Sub-commands are named commands as the first argument passed into a program, where each sub-command has it’s own unique set of required and optional arguments.
A well-known program with sub-commands is
git command-line program has various sub-commands such as:
Each one of these sub-commands has it’s own required and optional arguments.
If you find yourself starting to add options that are only applicable when certain other arguments are present, then it might be time to look into sub-commands.
argparse has sub-command support through the use of
add_subparsers(). The following working example shows a Python program which has two sub-commands,
add_subparsers() allows us to query the sub-command invoked through
The following code shows how this Python file can be called with command-line arguments from a shell/terminal:
argparse also provides nice help for these sub-commands:
This work is licensed under a Creative Commons Attribution 4.0 International License .
- Python Sets
- Python Classes And Object Orientated Design
- Python Type Annotations
- A Tutorial On geopandas
- Python And File Paths
- programming languages
- argument parser