Python argparse module usage guide
argparse is a core module used in the Python standard library for building command line tools, supporting parameter analysis, automatic generation of help information and error handling. Here are its core functions and usage methods:
- Basic usage
step:
Create a parser: Initialize the parser object through ArgumentParser and define program description information.
import argparse
parser = (description="Program Description")
Add parameters:
Positional parameters: Parameters that must be passed in order.
parser.add_argument("input_file", help="input file path")
Optional parameters: parameters starting with - or --, supporting short/long formats.
parser.add_argument("-v", "--verbose", action="store_true", help="Enable detailed mode")
Parse parameters: Call parse_args() to get the parse result.
args = parser.parse_args()
print(args.input_file)
- Parameter type and configuration
Type constraint: Specify parameter types (such as int, float) through type.
parser.add_argument("--size", type=int, default=10, help="value size")
Required parameters: Set required=True Force user input.
parser.add_argument("-o", "--output", required=True)
Mutexual Exclusive Parameters: Create a mutexual parameter group by add_mutually_exclusive_group().
group = parser.add_mutually_exclusive_group()
group.add_argument("--enable", action="store_true")
group.add_argument("--disable", action="store_true")
- Advanced features
Subcommand: Use a sub-parser to implement multi-level commands (similar to the git commit structure).
subparsers = parser.add_subparsers()
parser_a = subparsers.add_parser("cmd1", help="subcommand1")
parser_a.add_argument("--option")
Parameter action: Define parameter behavior through action (such as store_true to store boolean values).
parser.add_argument("--debug", action="store_true")
- Best Practices
Clear help information: Add a help description for each parameter to improve the ease of use of the tool.
Default value setting: Provide reasonable default values through default to reduce user input burden.
Error handling: Relying on argparse to automatically verify the legality of parameters and avoid manual verification.
Complete example
import argparse
def main():
parser = (description="File Processing Tool")
parser.add_argument("input", help="input file path")
parser.add_argument("-o", "--output", help="output file path", default="")
parser.add_argument("--size", type=int, default=100, help="process size")
parser.add_argument("-v", "--verbose", action="store_true", help="detailed mode")
args = parser.parse_args()
if:
print(f"processing {}, output to {}")
if name == "main":
main()
Running example:
python -o --size 200 -v
Summarize
argparse provides flexible command-line parameter parsing capabilities for the development of from simple scripts to complex tools. By using parameter types, subcommands, and mutex logic rationally, a user-friendly CLI application can be built.