How to Add Command Line Arguments to a Python Script

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:

import argparse

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 -h

$ ./test.py --help

You should get some output similar to this:

usage: test.py [-h]


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:

import argparse

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:

usage: test.py [-h] [print_string]


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.

import argparse

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.

$ ./test.py --print_string LinuxHint.com
LinuxHint.com

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.

import argparse

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:

$ ./test.py -p LinuxHint.com

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.

import argparse

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:

$ ./test.py -p LinuxHint.com

You should get an error like this:

usage: test.py [-h] [-p PRINT_STRING]

test.py: error: argument -p/--print_string: invalid int value: 'LinuxHint.com'

Supplying an integer value will give you correct result:

$ ./test.py -p 1000
1000

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.

import argparse

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:

$ ./test.py -p

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:

import argparse

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:

$ ./test.py -p “a” “b”

You should get some output like this:

['a', 'b']

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.



from Linux Hint https://ift.tt/3630Ghf

Post a Comment

0 Comments