智伤帝的个人博客

智伤帝

马上订阅 智伤帝的个人博客 RSS 更新: https://blog.l0v0.com/atom.xml

Python doit 库

2022年3月28日 15:50

前言

  代码开发的过程中可能遇到一些情况想要通过 代码 来自动执行命令行生成一些东西的情况。
  如果不使用框架进行管理,这些代码脚本就很零碎地散落在各个地方。
  因此就找到这个框架可以很方便管理多个任务,实现

Github 地址
官方说明文档

doit 的基本用法

  在 doit 执行命令的地方添加一个 dodo.py 的脚本
  doit 会去读取 dodo.py 里面命名开头为 task_ 的方法作为执行的命令。

1
2
3
4
5
6
7
8
9
10
11
def task_hello():
"""hello"""

def python_hello(targets):
with open(targets[0], "a") as output:
output.write("Python says Hello World!!!\n")

return {
'actions': [python_hello],
'targets': ["hello.txt"],
}

  比如添加上面的方法到 dodo.py 里面
  执行 doit list 可以罗列出当前的可执行的命令

1
2
3
4
F:\thm_git\adam_pose_editor>doit list
hello hello
F:\thm_git\adam_pose_editor>doit hello
. hello

  执行 doit hello 就会在 dodo.py 缩在目录下输出一个 hello.txt 的文件。
  这个就是 doit 的基本用法。

dodo.py 配置

https://pydoit.org/configuration.html

  可以使用 doit -f xxx/dodo.py 配置 dodo.py 的路径
  也可以使用 pyproject.toml 进行配置

1
2
[tool.doit]
dodoFile = "scripts/dodo.py"

task 配置

  dodo.py 的 task 支持导入
  只要是 task_ 前缀的方法就会自动识别。
  也可以给函数添加 create_doit_tasks 属性,这样就可以自动生成了。 文档链接

  利用这些机制,我搞了一个装饰器可以给 task 添加一个短名的方案。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
def add_short_name(short_name):
"""Doit for short decorator.

Args:
short_name (str): short alias name.

Returns:
callable: decoartor function.
"""

def decorator(func):
globals()["task_{0}".format(short_name)] = func # noqa: WPS421
return func

return decorator

@add_short_name(...

剩余内容已隐藏

查看完整文章以阅读更多