It should be taken into account that we should not handle sys.argv directly, mainly when our programs take complex parameters or multiple filenames. Alternatively, we should use Python's argparse library, which handles command-line arguments in a systematic way, making it accessible to write user-friendly command-line programs. In other words, Python has a module called argparse (https://docs.python.org/3/library/argparse.html) in the standard library for parsing command-line arguments. First, the program determines what arguments it requires. Then, argparse will work out how to parse these arguments to sys.argv. Also, argparse produces help and usage messages, and issues errors when invalid arguments are provided.
The minimum example to introduce this module is given here, argparse_minimal.py, which is shown as follows:
# Import the required packages
import argparse
# We first create the ArgumentParser object
# The created object 'parser' will have the necessary information
# to parse the command-line arguments into data types.
parser = argparse.ArgumentParser()
# The information about program arguments is stored in 'parser' and used when parse_args() is called.
# ArgumentParser parses arguments through the parse_args() method:
parser.parse_args()
Running this script with no parameters results in nothing being displayed to stdout. However, if we include the --help (or -h) option, we will get the usage message of the script:
usage: argparse_minimal.py [-h]
optional arguments:
-h, --help show this help message and exit
Specifying any other parameters results in an error, for example:
argparse_minimal.py 6
usage: argparse_minimal.py [-h]
argparse_minimal.py: error: unrecognized arguments: 6
Therefore, we must call this script with the -h argument. In this way, the usage message information will be shown. No other possibilities are allowed as no arguments are defined. In this way, the second example to introduce argparse is to add a parameter, which can be seen in the argparse_positional_arguments.py example:
# Import the required packages
import argparse
# We first create the ArgumentParser object
# The created object 'parser' will have the necessary information
# to parse the command-line arguments into data types.
parser = argparse.ArgumentParser()
# We add a positional argument using add_argument() including a help
parser.add_argument("first_argument", help="this is the string text in connection with first_argument")
# The information about program arguments is stored in 'parser'
# Then, it is used when the parser calls parse_args().
# ArgumentParser parses arguments through the parse_args() method:
args = parser.parse_args()
# We get and print the first argument of this script:
print(args.first_argument)
We added the add_argument() method. This method is used to specify what command-line options the program will accept. In this case, the first_argument argument is required. Additionally, the argparse module stores all the parameters, matching its name with the name of each added parameter—in this case, first_argument. Therefore, to obtain our parameter, we perform args.first_argument.
If this script is executed as argparse_positional_arguments.py 5, the output will be 5. However, if the script is executed without arguments as argparse_positional_arguments.py, the output will be as follows:
usage: argparse_positional_arguments.py [-h] first_argument
argparse_positional_arguments.py: error: the following arguments are required: first_argument
Finally, if we execute the script with the -h option, the output will be as follows:
usage: argparse_positional_arguments.py [-h] first_argument
positional arguments:
first_argument this is the string text in connection with first_argument
optional arguments:
-h, --help show this help message and exit
By default, argparse treats the options we give it as strings. Therefore, if the parameter is not a string, the type option should be established. We will see the argparse_sum_two_numbers.py script adding two arguments and, hence, these two arguments are of the int type:
# Import the required packages
import argparse
# We first create the ArgumentParser object
# The created object 'parser' will have the necessary information
# to parse the command-line arguments into data types.
parser = argparse.ArgumentParser()
# We add 'first_number' argument using add_argument() including a help. The type of this argument is int
parser.add_argument("first_number", help="first number to be added", type=int)
# We add 'second_number' argument using add_argument() including a help The type of this argument is int
parser.add_argument("second_number", help="second number to be added", type=int)
# The information about program arguments is stored in 'parser'
# Then, it is used when the parser calls parse_args().
# ArgumentParser parses arguments through the parse_args() method:
args = parser.parse_args()
print("args: '{}'".format(args))
print("the sum is: '{}'".format(args.first_number + args.second_number))
# Additionally, the arguments can be stored in a dictionary calling vars() function:
args_dict = vars(parser.parse_args())
# We print this dictionary:
print("args_dict dictionary: '{}'".format(args_dict))
# For example, to get the first argument using this dictionary:
print("first argument from the dictionary: '{}'".format(args_dict["first_number"]))
If the script is executed without arguments, the output will be as follows:
argparse_sum_two_numbers.py
usage: argparse_sum_two_numbers.py [-h] first_number second_number
argparse_sum_two_numbers.py: error: the following arguments are required: first_number, second_number
Additionally, if we execute the script with the -h option, the output will be as follows:
argparse_sum_two_numbers.py --help
usage: argparse_sum_two_numbers.py [-h] first_number second_number
positional arguments:
first_number first number to be added
second_number second number to be added
optional arguments:
-h, --help show this help message and exit
It should be taken into account that in the previous example, we introduced the possibility of storing arguments in a dictionary by calling the vars() function:
# Additionally, the arguments can be stored in a dictionary calling vars() function:
args_dict = vars(parser.parse_args())
# We print this dictionary:
print("args_dict dictionary: '{}'".format(args_dict))
# For example, to get the first argument using this dictionary:
print("first argument from the dictionary: '{}'".format(args_dict["first_number"]))
For example, if this script is executed as argparse_sum_two_numbers.py 5 10, the output will be as follows:
args: 'Namespace(first_number=5, second_number=10)'
the sum is: '15'
args_dict dictionary: '{'first_number': 5, 'second_number': 10}'
first argument from the dictionary: '5'
This was a quick introduction to both sys.argv and argparse. An advanced introduction to argparse can be seen at https://docs.python.org/3/howto/argparse.html. Additionally, its docs are quite detailed and meticulous and have covered plenty of examples (https://docs.python.org/3/library/argparse.html). At this point, you can now learn how to read and write images using argparse in your OpenCV and Python programs, which will be shown in the Reading and writing images section.