In this section, we are going to learn about parsing arguments and the module used to parse arguments.
Parsing command-line arguments
Command-line arguments in Python
We can start a program with additional arguments, in the command line. Python programs can start with command-line arguments. Let's look at an example:
$ python program_name.py img.jpg
Here, program_name.py and img.jpg are arguments.
Now, we are going to use modules to get the arguments:
Module |
Use |
Python version |
optparse |
Deprecated |
< 2.7 |
sys |
All arguments in sys.argv (basic) |
All |
argparse |
Building a command-line interface |
>= 2.3 |
fire |
Automatically generating Command-Line Interfaces (CLIs) |
All |
docopt |
Creating CLIs interfaces |
>= 2.5 |
Sys.argv
The sys module is used to access command-line parameters. The len(sys.argv) function contains the number of arguments. To print all of the arguments, simply execute str(sys.argv). Let's have a look at an example:
01.py
import sys
print('Number of arguments:', len(sys.argv))
print('Argument list:', str(sys.argv))
Output:
Python3 01.py img
Number of arguments 2
Arguments list: ['01.py', 'img']