跳转到主要内容
Development 工具让本地副作用显式:命令返回结果,并行任务返回任务记录,错误被格式化,代理设置带作用域。
当脚本或扩展需要围绕 HeavenBase 工作流的操作类 helper 时,请阅读本页。

1. 核心思想

这些 helper 面向产品表面之外的工作:运行命令、扇出本地任务、格式化有用错误、临时修改代理环境变量,或在 demo 运行期间重定向日志。 共同点是可逆与可见。helper 应让副作用更易检查、更易撤销,而不是藏在魔法 wrapper 后面。

2. 运行命令

需要把 stdout、stderr 与退出码当作数据时使用 cmd(...)
from heavenbase.utils import cmd

result = cmd(["python", "--version"])

if not result.ok:
    raise RuntimeError(result.err)

print(result.out)
调用方只需要某一字段时只请求该字段:
from heavenbase.utils import cmd

version = cmd(["python", "--version"], include="out")
handle = cmd(["python", "-m", "http.server", "8000"], wait=False, include="handle")
序列命令不会调用 shell,除非你传入 shell=True。对用户提供的值优先使用序列命令。

3. 映射有界工作

工作可并发且返回值必须保持输入顺序时使用 pmap(...)
from heavenbase.utils import pmap

items = [{"score": 3}, {"score": 1}, {"score": 2}]
scores = pmap(lambda score: score * 2, items, max_workers=4)
每项以关键字参数传入,因此批处理项必须是 mapping。 需要每项状态、捕获异常、耗时或进度回调时使用 batch(...)
from heavenbase.utils import batch

results = batch(lambda x: 10 / x, [{"x": 2}, {"x": 0}, {"x": 5}], max_workers=2)

failed = [result for result in results if not result.ok]
异步代码通过 abatch(...)abatch_stream(...) 使用相同契约。

4. 格式化错误与不匹配

校验应提示最接近的支持值时使用 raise_mismatch(...)
from heavenbase.utils import capture_error, error_str, raise_mismatch

try:
    raise_mismatch(["json", "yaml"], "jsno", name="format")
except ValueError as exc:
    message = error_str(exc, tb=False)
    record = capture_error(exc)
capture_error(...) 返回 ErrorRecord,可通过 record.reraise() 保留原始异常。

5. 使用作用域代理设置

某次操作需要临时 HTTP_PROXYHTTPS_PROXYNO_PROXY 环境变量时使用 NetworkProxy
from heavenbase.utils import NetworkProxy

with NetworkProxy(http_proxy="http://localhost:7890", no_proxy="localhost,127.0.0.1"):
    ...
上下文退出时会恢复已有环境值。传入空字符串会在该上下文内禁用对应代理变量。

6. 日志与彩色诊断

HeavenBase 日志输出用 get_logger(...);临时诊断路由用 redirect_logs(...)suppress_logs(...)
from heavenbase.utils import get_logger, redirect_logs, restore_logs, suppress_logs

logger = get_logger("heavenbase.docs")
logger.success("ready")

redirect_logs("demos/.temp/heavenbase.log")
try:
    logger.warning("written to the log file")
finally:
    restore_logs()

suppress_logs()
restore_logs()
cstr(...)color_success(...)strip_color(...) 等颜色 helper 用于终端诊断。不要把带颜色的字符串存入 JSON、行或基准测试产物。

Further Exploration

相关资源:
  • 文件系统 - 命令工作流使用的本地路径与文件。
  • 随机 - 并行测试与基准测试的可复现数据。
  • 配置 - 并行 worker 限制与日志的配置默认值。