
项目里总有些命令要反复敲:跑测试、打包、部署、清临时文件……每次手动来一遍既烦又容易漏步骤。invoke 就是用来解决这个问题的——把这些操作写成 Python 函数,统一用命令行调用。
invoke 是一个 Python 库,专注于“任务执行”。它最初从远程部署工具 Fabric 里拆出来,现在是独立的通用任务执行工具。
和 tox(主要管测试环境和打包)或 nox(灵活的测试运行器)不同,invoke 定位更宽泛——零散的独立脚本可以用它管,有依赖顺序的工作流也可以用它编排。
pip install invoke在项目根目录新建 tasks.py,这是 invoke 默认读取的任务文件。
用 @task 装饰器标记函数,函数的第一个参数必须是上下文参数(通常写成 c、ctx 或 context),用来执行 shell 命令和访问配置。
# tasks.py
frominvokeimporttask
@task
defhello(c):
"""打印欢迎信息"""
print("Hello, Automation!")
@task
defping_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 参数指定前置/后置任务:
@task
defclean(c):
c.run("rm -rf ./tmp/*")
@task
defbuild(c):
c.run("echo 正在编译...")
@task(pre=[clean], post=[build]) # 先清理,再运行本任务,最后构建
deftest(c):
c.run("pytest")执行 inv test 将按顺序运行 clean -> test -> build。
任务多了可以用 Collection 分模块管理:
# tasks.py
frominvokeimportCollection, task
importdeploy_tasks # 另一个定义了任务的模块
importtest_tasks
@task
deflint(c):
c.run("flake8 .")
# 创建一个命名空间集合,整合所有任务
namespace = Collection(lint, deploy_tasks, test_tasks)调用时用点号分隔:inv deploy-tasks.deploy-prod。
可以自动回应命令行程序的交互提示:
@task
defdangerous_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 的命令差异,脚本移植成本低用法不复杂,上手写几个任务就能感受到它的思路。进阶功能如配置管理、并行执行等可以查官方文档。
“无他,惟手熟尔”!有需要的用起来!
如果你觉得这篇文章有用,欢迎点赞、转发、收藏、留言、推荐❤!
本文分享自 Nicholas与Pypi 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体同步曝光计划 ,欢迎热爱写作的你一起参与!