Command-line Argument Parsing in Python with argparse
Command-line scripts are vital tools in the arsenal of many programmers, especially those who work in the field of automation. One of the most important aspects of command-line scripts is the ability to take input from the user and work with it.
This is where the argparse
module comes in, which allows for easy argument parsing in Python. In this article, we will explore the argparse
module, how to create an argument parser with it, and some of its useful methods.
1) Creating the Argument Parser using argparse.ArgumentParser()
The argparse
module provides the ArgumentParser
class, which allows us to easily create an argument parser object. The first step is to import the module as shown below:
import argparse
We can then use the argparse.ArgumentParser()
method to create our argument parser object. This method takes some arguments, such as “description” and “epilog”, that provide information about the program being executed.
These are optional arguments that can be supplied if desired.
parser = argparse.ArgumentParser(description='Program to do something useful')
2) Adding arguments to the parser object with parser.add_argument()
Once the argument parser object has been created, we can add arguments to it using the parser.add_argument()
method.
This method allows us to define the different arguments that our program will accept. There are several parameters that can be passed to this method, including the argument names, whether the argument is optional, and any help text associated with it.
parser.add_argument('--input', dest='input_file', help='Path to Input file', required=True)
In the above example, the “–input” argument is defined, and its destination is provided as “input_file”. Any help text for the argument is included in the “help” parameter, and “required=True” tells us that the argument is mandatory.
3) Creating the Argument Parser with optional parameters: prog and usage
When creating an argument parser object, we can add some optional parameters to customize its behavior. One such parameter is “prog”, which specifies the name of our program.
parser = argparse.ArgumentParser(prog='my_program')
Another optional parameter is “usage”, which specifies a usage message for our program.
parser = argparse.ArgumentParser(usage='%(prog)s [options] input output')
4) Using short names for optional parameters with parser.add_args()
The argparse
module allows us to use short names for optional parameters.
This is done by simply notating the short name as a single character after the longer argument name.
parser.add_argument('-f', '--file', dest='input_file', help='Path to Input file', required=True)
In the above example, the “-f” option is used as a short name for the “–file” option.
Conclusion
Overall, the argparse
module provides an easy and convenient way to handle arguments in command-line scripts. By creating an argument parser object and using the add_argument()
method, we can easily define the arguments for our program.
The module also includes other useful methods, such as creating an Argument Parser with optional parameters and using short names for optional parameters. With this knowledge, you can create more efficient and effective command-line scripts in Python.
3) Example demonstration of argparse module usage
In this section, we will demonstrate how to use the argparse
module in a practical sense. We will create a simple program that takes two arguments – a string and a number.
The program then prints the string repeated for the specified number of times. Let’s dive in and see how it’s done.
import argparse
def repeat_string(string, times):
for i in range(times):
print(string)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--string', help='The string to be repeated')
parser.add_argument('--times', help='Number of times to repeat the string', type=int)
args = parser.parse_args()
if args.string and args.times:
repeat_string(args.string, args.times)
else:
parser.print_help()
In the above example, we created a function called “repeat_string” that takes in two arguments – a string and a number. It then prints the string the specified number of times in a loop.
Next, we create our argument parser object using argparse.ArgumentParser()
. We then use parser.add_argument()
method to create our two arguments – “–string” and “–times”.
We’ve also included “help” messages via the “help” parameter to let the user know what input is expected for each argument. The “type=int” parameter on the “–times” argument ensures that the argument is converted to an integer.
We use parser.parse_args()
to parse the command-line arguments provided by the user. The if statement checks that both arguments were supplied with valid inputs.
If they were, the repeat_string
function is called with the two arguments; otherwise, the help message is printed via parser.print_help()
.
4) Handling erroneous and correct input parameters
One of the benefits of using the argparse
module is that it can handle type checking and validation of input parameters. In the example above, the “type=int” parameter on the “–times” argument ensures that the argument is converted to an integer.
If the user provides an invalid input type, such as a string, the argparse
module will raise a TypeError
exception with a helpful error message. Additionally, if the user fails to provide a required argument, such as the “–string” argument, argparse
will raise a “required” argument error with a helpful error message.
It is important to include error handling in our programs using argparse
to prevent erroneous input from crashing our programs in unexpected ways.
Summary
In summary, the argparse
module provides an easy way to handle command-line arguments in Python. We can create an ArgumentParser object using argparse.ArgumentParser()
, and use the add_argument()
method to define the arguments for our program.
We also saw that the argparse
module can handle type checking and validation of input parameters. Lastly, we demonstrated a practical example of implementing argparse
in Python, handling both correct and erroneous input parameters.
Overall, learning how to effectively use the argparse
module can help you write more efficient and user-friendly command-line programs in Python. In this article, we explored the argparse
module in Python and how to create an argument parser to handle command-line inputs.
We learned how to create an argument parser object using argparse.ArgumentParser()
and how to add arguments to it using parser.add_argument()
. We also covered the Optional parameters prog
and usage
that can be used to customize the Argument Parser.
Additionally, we demonstrated a practical example of the argparse
module implementation and the importance of error-handling. The main takeaway is that argparse
is a useful module to know for creating efficient and user-friendly command-line programs in Python.