实现说明
文件的主干是一个循环——while sorter.is_active()。从 graphlib 导入了 CycleError、TopologicalSorter——导入清单就是这段代码触碰的库表面。
顶层就这几处状态:build、sorter。
使用要点
graphlib必须先装好——示例直接导入它们。- 直接运行文件,输出会带上标签,比如
static order:、parallel batch:、cycle:——输出的每一行都能指回产生它的那次调用。
常见问题
需要安装第三方包吗?
需要——graphlib。运行前请先加入项目依赖。
核心语句
except CycleError as exc:
print("cycle:", exc)
代码示例
from graphlib import CycleError, TopologicalSorter
build = {
"checkout": set(),
"install": {"checkout"},
"lint": {"install"},
"test": {"install"},
"bundle": {"install"},
}
print("static order:", " -> ".join(TopologicalSorter(build).static_order()))
# prepare/get_ready/done: each round hands out the batch of nodes with no unfinished dependencies (runnable in parallel)
sorter = TopologicalSorter(build)
sorter.prepare()
while sorter.is_active():
batch = sorted(sorter.get_ready())
print("parallel batch:", batch)
sorter.done(*batch)
try:
TopologicalSorter({"a": {"b"}, "b": {"a"}}).prepare()
except CycleError as exc:
print("cycle:", exc)