调用对于使用Python而不是麻烦(Shell脚本)很有用 您所在的位置:网站首页 python调用shell脚本很慢 调用对于使用Python而不是麻烦(Shell脚本)很有用

调用对于使用Python而不是麻烦(Shell脚本)很有用

2023-03-12 00:01| 来源: 网络整理| 查看: 265

有一个名为Invoke的轻量级Python任务运行程序。

使用

@task装饰器创建一个函数,并使用c.run()如下执行命令。

task.py

12345from invoke import * @task def install(c):     c.run("pip install -r requirements.txt")

为此:

12$ pip3 install invoke $ invoke install

用for语句重复该语句,如下所示。

task.py

12345@task def build(c):     packages = ["Client", "Server", "Tester"]     for name in packages:         c.run(f"go build cmd/{name} -o out/{name}")

对于

依赖项,请将依赖函数传递给@task的参数。

task.py

1234567891011@task def build(c):     c.run("go build -o out") @task(build) def test(c):     c.run("go test") @task(test) def release(c):     c.run("zip out.zip out/")

当通过

退出代码分支时,将warn=True添加到参数中并使用返回值.ok和.failed。

task.py

1234567@task def build(c):     if c.run("test -e ./node_modules", warn=True).failed:         c.run("npm install")     if c.run("test -e out", warn=True).ok:         c.run("rm -rf out")     c.run("tsc")

要移动

目录,请在with子句

中调用c.cd()

task.py

12345678@task def build(c):     with c.cd("client"):         c.run("go build")         c.run("go test")     with c.cd("server"):         c.run("go build")         c.run("go test")

如果为

函数设置参数,它将成为命令的参数。

task.py

1234567@task def release(c, gs_path, force=False):     if force:         c.run("git push -f")     else:         c.run("git push")     r = c.run(f"gsutil rsync . {gs_path}") 1$ invoke release --gs-path gs://release-gcs/ --force

要使用它代替

sed,可以使用r.stdout输出标准输出,但是要将其用作标准输入,请将其输出到tempfile一次。

task.py

1234567891011import tempfile @task def release(c):     r = c.run("cat deployment.yaml")     yaml = r.stdout.replace("__IP__", "3.4.5.6")     with tempfile.NamedTemporaryFile() as tmp:         with os.open(tmp.name) as f:             f.write(yaml)         c.run(f"cat {tmp.nmae} | kubectl apply -f -")

我制作了这本小册子作为备忘单,并作为技术手册5中的免费论文分发了。您也可以下载它,因此请根据需要使用它!

我制作了更详细的用法手册,并在技术手册5中进行了分发。



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有