Introduction to argparse
In Python, the argparse module is used for parsing command-line arguments. It makes it easy to write user-friendly command-line interfaces and handle various types of inputs, such as flags, options, and positional arguments. The argparse module is part of the Python standard library, so no external dependencies are required.
Basic usage
The basic steps for using argparse in your Python script are as follows:
- Import the argparse module
- Create an ArgumentParser object
- Add arguments using the add_argument() method
- Parse the command-line arguments using the parse_args() method
Here is an example of a Python script that uses argparse to accept a single argument:
import argparse parser = argparse.ArgumentParser(description='A simple script that accepts a message argument.') parser.add_argument('message', help='The message to print') args = parser.parse_args() print(args.message)
In this script, we import the argparse module, create an ArgumentParser object with a description, add a positional argument called message
with a help message, and then parse the command-line arguments using the parse_args()
method. Finally, we print out the message
argument.
Here is an example of how to run this script from the command line:
$ python myscript.py "Hello, world!" Hello, world!
Adding flags and options
In addition to positional arguments, argparse also supports adding optional flags and options to your script.
Here is an example of a Python script that accepts a flag and an optional option:
import argparse parser = argparse.ArgumentParser(description='A simple script that accepts a message argument.') parser.add_argument('message', help='The message to print') parser.add_argument('-u', '--uppercase', action='store_true', help='Print the message in uppercase') parser.add_argument('-r', '--repeat', type=int, default=1, help='Print the message multiple times') args = parser.parse_args() message = args.message.upper() if args.uppercase else args.message for i in range(args.repeat): print(message)
In this script, we add two optional arguments using the add_argument()
method. The -u
or --uppercase
flag is defined with the store_true
action, which means that if it is present, the value will be set to True
. The -r
or --repeat
option is defined with a type
of int
, a default value of 1
, and a help message.
Conclusion
In this post, we covered the basics of how to use the Python argparse module for command-line argument parsing. We looked at how to add positional arguments, optional flags, and options to your script. Argparse is a powerful module that makes it easy to write user-friendly command-line interfaces for your Python scripts.