Working with Positional Arguments
Positional arguments are the core of the argparse
module. They are used to define the required input parameters for your program. Let's explore how to work with positional arguments in more detail.
Defining Positional Arguments
To define a positional argument, you can use the add_argument()
method of the ArgumentParser
object. The first argument to add_argument()
is the name of the positional argument, which will be used to access the value of the argument in your code.
Example:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("filename", help="Input file name")
parser.add_argument("output_dir", help="Output directory")
args = parser.parse_args()
print(f"Input file: {args.filename}")
print(f"Output directory: {args.output_dir}")
In this example, the filename
and output_dir
arguments are defined as positional arguments.
Handling Multiple Positional Arguments
You can define multiple positional arguments by calling the add_argument()
method multiple times. The arguments must be provided in the order they are defined.
Example:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("operation", help="Operation to perform (add, subtract, multiply, divide)")
parser.add_argument("num1", type=float, help="First number")
parser.add_argument("num2", type=float, help="Second number")
args = parser.parse_args()
if args.operation == "add":
result = args.num1 + args.num2
elif args.operation == "subtract":
result = args.num1 - args.num2
## Additional operations omitted for brevity
print(f"Result: {result}")
In this example, the user must provide the operation
, num1
, and num2
arguments in that order when running the script.
Handling Missing Positional Arguments
If a required positional argument is not provided, the argparse
module will raise an error. You can handle this by setting the required
parameter to True
when defining the argument.
Example:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("filename", required=True, help="Input file name")
parser.add_argument("output_dir", required=True, help="Output directory")
args = parser.parse_args()
print(f"Input file: {args.filename}")
print(f"Output directory: {args.output_dir}")
In this example, if the user does not provide both the filename
and output_dir
arguments, the argparse
module will raise an error.
By understanding how to define and work with positional arguments, you can create more robust and user-friendly command-line interfaces for your Python applications.