
项目里总有些命令要反复敲:跑测试、打包、部署、清临时文件……每次手动来一遍既烦又容易漏步骤。invoke 就是用来解决这个问题的——把这些操作写成 Python 函数,统一用命令行调用。
往期阅读>>>
Python 20 个文本分析的库:效率提升 10 倍的秘密武器
Python 自动化管理Jenkins的15个实用脚本,提升效率
App2Docker:如何无需编写Dockerfile也可以创建容器镜像
Python 自动化识别Nginx配置并导出为excel文件,提升Nginx管理效率
invoke 是一个 Python 库,专注于“任务执行”。它最初从远程部署工具 Fabric 里拆出来,现在是独立的通用任务执行工具。
和 tox(主要管测试环境和打包)或 nox(灵活的测试运行器)不同,invoke 定位更宽泛——零散的独立脚本可以用它管,有依赖顺序的工作流也可以用它编排。
pip install invoke在项目根目录新建 tasks.py,这是 invoke 默认读取的任务文件。
用 @task 装饰器标记函数,函数的第一个参数必须是上下文参数(通常写成 c、ctx 或 context),用来执行 shell 命令和访问配置。
# tasks.pyfrominvokeimporttask@taskdefhello(c):"""打印欢迎信息"""print("Hello, Automation!")@taskdefping_service(c, url="http://example.com"):"""测试网络服务连通性"""result = c.run(f"curl -I {url}", hide=True, warn=True)ifresult.ok:print(f"{url} 服务正常!")else:print(f"{url} 访问失败。")
# 列出所有可用任务及其描述inv --list# 输出:hello, ping_service# 运行 hello 任务inv hello# 输出:Hello, Automation!# 运行 ping_service 任务,使用默认参数inv ping-service# 输出:http://example.com 服务正常!# 运行 ping_service 任务,并传入自定义参数inv ping-service --url="https://api.github.com"
用 pre 和 post 参数指定前置/后置任务:
@taskdefclean(c):c.run("rm -rf ./tmp/*")@taskdefbuild(c):c.run("echo 正在编译...")@task(pre=[clean], post=[build]) # 先清理,再运行本任务,最后构建deftest(c):c.run("pytest")
执行 inv test 将按顺序运行 clean -> test -> build。
任务多了可以用 Collection 分模块管理:
# tasks.pyfrominvokeimportCollection, taskimportdeploy_tasks# 另一个定义了任务的模块importtest_tasks@taskdeflint(c):c.run("flake8 .")# 创建一个命名空间集合,整合所有任务namespace = Collection(lint, deploy_tasks, test_tasks)
调用时用点号分隔:inv deploy-tasks.deploy-prod。
可以自动回应命令行程序的交互提示:
@taskdefdangerous_operation(c):responses = {r"Are you sure\? \[y/N\] ": "y\n"}c.run("rm -rf /tmp/some-cache", responses=responses)
invoke 也可以直接拿来开发小型命令行工具,不需要再引入 argparse 或 click。
本地开发工作流:inv install 装依赖、inv test 跑测试、inv run 起本地服务
构建与部署:inv build 打包、inv deploy-staging / inv deploy-prod 分环境部署
运维脚本:inv check-disk 查磁盘、inv backup-db 备份数据库、inv status 看服务状态
跨平台脚本:c.run() 能处理 Windows/Linux/macOS 的命令差异,脚本移植成本低
用法不复杂,上手写几个任务就能感受到它的思路。进阶功能如配置管理、并行执行等可以查官方文档。
