Command-line argument parsing is an essential part of many Python applications. The argparse
module in Python’s standard library provides a convenient way to define and parse command-line arguments.
In this blog post, we will walk through a series of examples to illustrate how to use argparse
for testing and debugging purposes.
Example 1: Basic argument parsing
Let’s start with a simple example of parsing a single positional argument using argparse
.
First, import the argparse
module:
import argparse
Define the argument parser and add a positional argument:
parser = argparse.ArgumentParser()
parser.add_argument('filename', help='Name of the file')
Parse the command-line arguments:
args = parser.parse_args()
Access the parsed argument:
print(args.filename)
Example 2: Handling optional arguments
Now, let’s explore how to handle optional arguments using argparse
.
Add an optional argument to the parser:
parser.add_argument('-v', '--verbose', action='store_true', help='Enable verbose mode')
Parse the command-line arguments as before, and access the optional argument:
if args.verbose:
print('Verbose mode activated')
Example 3: Specifying argument types
Sometimes, you may need to specify the type of an argument. argparse
supports various built-in data types and allows you to define custom types.
Add a positional argument with a specified type:
parser.add_argument('num', type=int, help='An integer')
Parse the command-line arguments and access the typed argument:
print(f'The square of {args.num} is {args.num ** 2}')
Example 4: Handling multiple arguments
argparse
also supports parsing multiple arguments of the same type.
Add an argument with multiple values:
parser.add_argument('values', nargs='+', type=float, help='A list of floating-point numbers')
Parse the command-line arguments and access the multiple argument values:
for value in args.values:
print(value)
Conclusion
In this blog post, we explored how to use argparse
for testing and debugging purposes. We covered basic argument parsing, handling optional arguments, specifying argument types, and handling multiple arguments.
The argparse
module in Python provides a powerful and flexible way to parse command-line arguments, making it easier for developers to create user-friendly command-line interfaces.
Remember to refer to the official Python documentation for more detailed information and examples on using argparse
: argparse - Parser for command-line options, arguments and sub-commands
Happy testing and debugging with argparse
in Python!