If you have developed a Python script or application meant to be primarily run in terminal emulators or even GUI apps, adding command line arguments can improve its useability, code readability, application structure and overall user friendliness of the application for the end users. These command line arguments are also called “options” or “switches” and work similarly to arguments you usually see in bash scripts and other C / C++ based programs.
To add arguments to Python scripts, you will have to use a built-in module named “argparse”. As the name suggests, it parses command line arguments used while launching a Python script or application. These parsed arguments are also checked by the “argparse” module to ensure that they are of proper “type”. Errors are raised if there are invalid values in arguments.
Usage of the argparse module can be best understood through examples. Below are some code samples that will get you started with the argparse module.
Example 1: Generate Help Argument and Message
Consider the code sample below:
parser = argparse.ArgumentParser(description='A test program.')
args = parser.parse_args()
The first statement imports the “argparse” module. Next, a new instance of “ArgumentParser” object is created and a short description for the program is supplied as an argument. The ArgumentParser object is needed to convert command line argument values to data types understood by Python. This is done by the “parse_args” method of ArgumentParser object, as shown in the last statement.
Assuming that you have saved the code sample stated above in a file named “test.py”, running the commands below will get you help messages related to the program.
$ ./test.py --help
You should get some output similar to this:
A test program.
optional arguments:
-h, --help show this help message and exit
Note that no logic to handle parsed arguments and convert them to objects has been added to the code sample mentioned above. Hence, help messages for individual arguments are not shown in the output. Once you add logic for handling values of parsed arguments in your program, help messages will start showing description for individual arguments.
Example 2: Handle a String Argument
To add arguments acceptable by your python script, you need to use the “add_argument” method. Take a look at the following code:
parser = argparse.ArgumentParser(description='A test program.')
parser.add_argument("print_string", help="Prints the supplied argument.")
args = parser.parse_args()
print(args.print_string)
A new statement has been added showing use of the “add_argument” method. Any argument added when launching the script will be treated as a “print_string” object by “ArgumentParser”.
Note that by default, “add_argument” method treats values retrieved from arguments as strings, so you don’t have to explicitly specify the “type” in this case. A default value of “None” is also assigned to added arguments, unless overridden.
Once again take a look at the help message:
A test program.
positional arguments:
print_string Prints the supplied argument.
optional arguments:
-h, --help show this help message and exit
One of the lines in output says “positional arguments”. Since no keyword for argument is defined, currently the argument is treated as a “positional argument” where the order and position of supplied argument has direct effect on the program. Positional arguments are also mandatory, unless you manually change their behavior.
To define and parse optional arguments, you can use “–” (double dash) and change their default values using the “default” argument.
parser = argparse.ArgumentParser(description='A test program.')
parser.add_argument("--print_string", help="Prints the supplied argument.", default="A random string.")
args = parser.parse_args()
print(args.print_string)
Now when you run “test.py” script without any argument, you should get “A random string.” as output. You can also optionally use the “–print_string” keyword to print any string of your choice.
Note that you can make an optional argument mandatory by using an additional “required=True” argument.
Lastly, you can also define shorthand versions of the argument using “-” (single dash) to reduce verbosity.
parser = argparse.ArgumentParser(description='A test program.')
parser.add_argument("-p", "--print_string", help="Prints the supplied argument.", default="A random string.")
args = parser.parse_args()
print(args.print_string)
Running the following command should give you same result as above:
Example 3: Handle an Integer Argument
To handle arguments that need integer values, you need to set the “type” keyword to “int” to allow validation and throw errors in case the condition is not met.
parser = argparse.ArgumentParser(description='A test program.')
parser.add_argument("-p", "--print_string", help="Prints the supplied argument.", type=int)
args = parser.parse_args()
print(args.print_string)
Try running the following command:
You should get an error like this:
test.py: error: argument -p/--print_string: invalid int value: 'LinuxHint.com'
Supplying an integer value will give you correct result:
Example 4: Handle True and False Toggles
You can pass arguments without any values to treat them as True and False flags using the “action” argument.
parser = argparse.ArgumentParser(description='A test program.')
parser.add_argument("-p", "--print_string", help="Prints the supplied argument.", action="store_true")
args = parser.parse_args()
print(args.print_string)
Run the command below to get a simple “True” as the output:
If you run the script without the “-p” argument, a “False” value will be assigned instead. The value “store_true” of the “action” keyword assigns a “True” value to the “print_string” variable whenever the “-p” argument is explicitly specified, otherwise False is assigned to the variable.
Example 5: Treat Argument Values as List
If you want to get multiple values at once and store them in list, you need to supply “nargs” keyword in following format:
parser = argparse.ArgumentParser(description='A test program.')
parser.add_argument("-p", "--print_string", help="Prints the supplied argument.", nargs='*')
args = parser.parse_args()
print(args.print_string)
Run the following command to test the code above:
You should get some output like this:
Conclusion
The “argparse” module is pretty comprehensive with tons of options to tweak behaviour of command line applications and parse user supplied values. These examples touch only the basic usage of the “argparse” module. For advanced and complex applications, you may need different implementations. Visit the official documentation for a full explanation of the module.