Using Python's argparse Module: Basics, Examples, and Advanced Features
This article introduces Python's built‑in argparse module, explains how to create an ArgumentParser, add positional and optional arguments, set types, defaults, mutually exclusive groups, sub‑commands, and demonstrates running scripts with various command‑line options.
The argparse module is part of Python's standard library and simplifies the creation of user‑friendly command‑line interfaces by automatically generating help messages and parsing arguments.
Basic Usage – Import argparse , create an ArgumentParser object, add arguments, and call parse_args() to obtain the parsed values.
import argparse
# 创建解析器
parser = argparse.ArgumentParser(description='命令行示例')
# 添加参数
parser.add_argument('--name', type=str, default='world', help='你的名字')
# 解析参数
args = parser.parse_args()
print(f"你好, {args.name}")The example defines an optional --name argument with a default value of 'world' ; providing --name on the command line overrides the default.
Detailed Examples
Adding a positional argument:
parser.add_argument('filename', type=str, help='要处理的文件名')Adding an optional flag with a short alias:
parser.add_argument('--verbose', '-v', action='store_true', help='启用详细输出')Specifying the argument type:
parser.add_argument('--number', type=int, help='一个整数')Setting a default value:
parser.add_argument('--output', default='output.txt', help='输出文件名')Handling a boolean flag:
parser.add_argument('--debug', action='store_true', help='启用调试模式')Creating a mutually exclusive group:
group = parser.add_mutually_exclusive_group()
group.add_argument('--extract', action='store_true', help='提取操作')
group.add_argument('--compress', action='store_true', help='压缩操作')Supporting sub‑commands:
subparsers = parser.add_subparsers(help='命令帮助')
parser_a = subparsers.add_parser('command_a', help='命令A的帮助')
parser_a.add_argument('--option', help='选项')Running the Program
Assuming the script is saved as example.py :
python example.py input.txtProviding optional arguments:
python example.py --verbose --number=5Viewing help information:
python example.py -hThe argparse module automatically handles argument parsing, error checking, and help generation, making it easier to develop both simple scripts and complex command‑line applications.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.