Python 的 argparse 模块是标准库中用于解析命令行参数和选项的工具,它可以帮助开发者编写用户友好的命令行接口(CLI)。
CLI 是 Command-Line Interface(命令行界面)的缩写。
GUI 工具是 "Graphical User Interface"(图形用户界面)的缩写。
1. 基本用法
argparse 的核心步骤包括:
- 创建
ArgumentParser对象。 - 添加参数(位置参数、可选参数)。
- 解析命令行参数。
- 使用解析后的参数。
import argparse
# 1. 创建 ArgumentParser 对象
parser = argparse.ArgumentParser(description="这是一个示例程序")
# 2. 添加参数
parser.add_argument("--input", type=str, help="输入文件路径")
parser.add_argument("--output", type=str, help="输出文件路径")
parser.add_argument("--verbose", action="store_true", help="启用详细输出")
parser.add_argument("count", type=int, help="重复次数(位置参数)")
# 3. 解析参数
args = parser.parse_args()
# 4. 使用参数
print(f"输入文件: {args.input}")
print(f"输出文件: {args.output}")
print(f"详细模式: {'启用' if args.verbose else '禁用'}")
print(f"重复次数: {args.count}")
运行示例
python script.py --input input.txt --output output.txt --verbose 3
输出:
输入文件: input.txt
输出文件: output.txt
详细模式: 启用
重复次数: 3
2. 参数类型
type:指定参数的类型(如str、int、float等)。choices:限制参数的可选值。default:设置默认值。
parser.add_argument("--mode", type=str, choices=["train", "test"], default="train", help="运行模式")
3. 可选参数 vs 位置参数
- 可选参数:以
--或-开头(如--input)。 - 位置参数:不带前缀,按顺序传递(如
count)。
4. 布尔标志(Flag)
- 使用
action="store_true"或action="store_false"实现布尔标志。
示例:
parser.add_argument("--debug", action="store_true", help="启用调试模式")
运行:
python script.py --debug
输出:
调试模式: 启用
5. 参数分组
- 使用
add_argument_group对参数进行分组,提高可读性。
示例:
group = parser.add_argument_group("高级选项") group.add_argument("--threads", type=int, default=1, help="线程数")
6. 帮助信息
ArgumentParser会自动生成帮助信息(通过-h或--help查看)。
python script.py -h
输出:
usage: script.py [-h] [--input INPUT] [--output OUTPUT] [--verbose] count
这是一个示例程序
positional arguments:
count 重复次数(位置参数)
optional arguments:
-h, --help show this help message and exit
--input INPUT 输入文件路径
--output OUTPUT 输出文件路径
--verbose 启用详细输出
自动化框架中示例:
def run_main():
report_dir = PROJECT_FILE_PATH.test_case_report_path
web_case_dir = PROJECT_FILE_PATH.test_web_ui_case_path
api_case_dir = PROJECT_FILE_PATH.test_api_case_path
generate_test_report = PROJECT_FILE_PATH.generate_test_report_path
parser = argparse.ArgumentParser(prog='自动化测试命令行')
parser.add_argument('-w', '--web', action='store_true', help='执行web用例')
parser.add_argument('-i', '--api', action='store_true', help='执行api用例')
parser.add_argument('-a', '--all', action='store_true', help='执行web与api用例')
parser.add_argument('-x', '--xdist', action='store_true', help='并发执行web与api用例')
parser.add_argument('-cls', '--clear', default='1', help='是否清理历史报告数据:0.否,1.是 (默认 1)', type=str)
parser.add_argument('-g', '--generate', default='1', help='是否自动生成用例数据:0.否,1.是 (默认 1)', type=str)
args = parser.parse_args()
if args.clear == '1':
logger.info('开始清理历史报告数据')
environment_init()
if args.generate == '1':
logger.info('开始生成用例数据')
generate_test_case()
if args.api:
os.chdir(str(api_case_dir))
os.system(f'pytest -sv --alluredir={report_dir / "allure-results"}')
if args.web:
os.chdir(str(web_case_dir))
os.system(f'pytest -sv --alluredir={report_dir / "allure-results"} ')
if args.all:
os.system(f'pytest -sv --alluredir={report_dir / "allure-results"} --reruns 2 --reruns-delay 2')
if args.xdist:
os.system(f'pytest -sv --alluredir={report_dir / "allure-results"} --reruns 2 --reruns-delay 2')
with DbConnectionFactory() as db_factory:
sqlite_conn = db_factory.create_connection('sqlite', db_path=ProjectFilePath().test_result_db_path).connect()
fail_total = sqlite_conn.select('test_result_tb', ["count(1)", ], where={"execution_result": "fail"})[0][0]
# 如果失败数量是0直接发送测试报告
# if fail_total == 0:
# os.system(f'nohup python3 {generate_test_report} -a -rb 1 > mylog.log 2>&1 &')
# else:
# os.system(f'nohup python3 {generate_test_report} -a -trb 1 > mylog.log 2>&1 &')
- THE END -
最后修改:2025年6月26日
非特殊说明,本博所有文章均为博主原创。
共有 0 条评论