Tested on:Python3
0

Python Argparse massively simplifies parsing complex command line parameters

As the complexity of programs increases, the configuration effort for the user increases as well. Large programs often use configuration files, some with a graphical interface. But for many programs, well-defined command line arguments are sufficient. Since the import of parameters for complex programs is a hassle and bug-prone, the powerful Python module Argparse helps with this task.
This tutorial gives a little insight into the various uses of this module.

Argparse Setup
To read the command line parameters, an instance of ArgumentParser from the argparse module must be instantiated. A text
describing the program for the terminal help needs to be passed:

Then, ArgumentParser is complemented step by step with parameters to parse.

Integer with min and max values
Very useful is the parsing of an integer with minimum and maximum values, for example for setting the debug level. This is how:

nargs is the number of parameters expected after -d; the '?' means that a single parameter is expected that will not be stored in a list. choices is a list with all legal values of debug, here the range [1, 2, 3, 4, 5]. metavar is an additional hint for the terminal help and default gives debug a default value.

Boolean parameter
An other important argument type is the boolean parameter or flag. For example, the flag -g could be used for enabling the graphical mode of the program.

action = ‘store_true’ ensures that True is stored for gui when the -g flag is passed on the command line.

String parameter
String parameters are very frequent, for example for passing a path to the script. Here, the path behind -o should be the output path of the script.

Parsing arguments
After defining all parameters, they can be parsed with

Parameters can then be accessed like

Download the demo script and start it for example with

Full script
Click on Full Script to show all of the code.

Links
Argparse Documentation: https://docs.python.org/3/library/argparse.html

Knight of Pi

Johannes Bergs aka Knight of Pi. Diploma in Bioinformatics, some Webdesign and Python coding then. Living in the beautiful city of Vienna.

Comment

Time limit is exhausted. Please reload CAPTCHA.