这组 Bash 脚本保留三个原始用途:按指定 epoch 批次评估 PVNet、整理 lm/olm 并生成 ZIP,以及用命令替换保存当前目录。自动化前先写清输入、失败后的数据位置和恢复方法;“跑完循环”不等于过程中的修改都已恢复。
批次评估:恢复运行前的配置原文
跳转到“批次评估:恢复运行前的配置原文”原脚本按 34 个指定 epoch 调用 run.py。列表从 69 到 239,但其中没有 169,不能简化成一个连续步进序列。原来的最后一行把 cfg.test.epoch 写成 169,只能恢复“原值恰好为 169”的情况;失败或中断还会跳过这行。
下面保存为 evaluate-epochs.sh,以项目根目录为唯一参数,使用 Bash 与 Python 3。项目中应已有 run.py、configs/linemod.yaml 和 lib/config/config.py,配置里只能有一条独立的 cfg.test.epoch = ... 赋值。不要同时运行其他会修改此配置的程序。
#!/usr/bin/env bashset -euo pipefailproject=${1:?Usage: bash evaluate-epochs.sh PROJECT_DIRECTORY}cd -- "$project"config='lib/config/config.py'run_script='run.py'output_file='mycleanduck.log'if [[ ! -f "$config" || -L "$config" ]]; then printf 'Expected a regular config file: %s\n' "$config" >&2 exit 1fiif [[ ! -f "$run_script" || ! -f 'configs/linemod.yaml' ]]; then printf 'Missing run.py or configs/linemod.yaml\n' >&2 exit 1ficommand -v python3 >/dev/null
# Refuse to overwrite a log from an earlier run.(set -o noclobber; : > "$output_file")backup=$(mktemp "${config}.backup.XXXXXX")if ! cp -p -- "$config" "$backup"; then printf 'Backup failed; inspect %s\n' "$backup" >&2 exit 1fichild_pid=''restore() { status=$? trap - EXIT INT TERM if ! cp -p -- "$backup" "$config"; then printf 'Restore failed; backup retained at %s\n' "$backup" >&2 exit 1 fi rm -f -- "$backup" exit "$status"}stop_child() { code=$1 trap '' INT TERM if [[ -n "$child_pid" ]]; then kill -TERM -- "$child_pid" 2>/dev/null || : wait "$child_pid" 2>/dev/null || : fi exit "$code"}trap restore EXITtrap 'stop_child 130' INTtrap 'stop_child 143' TERM
epochs=(69 74 79 84 89 94 99 104 109 114 119 124 129 134 139 144 149 154 159 164 174 179 184 189 194 199 204 209 214 219 224 229 234 239)for epoch in "${epochs[@]}"; do printf 'Running epoch=%s\n' "$epoch" python3 - "$config" "$epoch" <<'PY'import pathlibimport reimport sys
file = pathlib.Path(sys.argv[1])data = file.read_bytes()pattern = re.compile(rb'^([ \t]*cfg\.test\.epoch[ \t]*=[ \t]*)[^\r\n]*(\r?)$', re.M)if len(pattern.findall(data)) != 1: raise SystemExit('Expected exactly one cfg.test.epoch assignment')epoch = sys.argv[2].encode('ascii')file.write_bytes(pattern.sub(lambda m: m[1] + epoch + m[2], data))PY python3 "$run_script" --type evaluate --cfg_file configs/linemod.yaml \ test.dataset LinemodOccTest model mycleanduck cls_type duck \ >> "$output_file" 2>&1 & child_pid=$! if wait "$child_pid"; then child_pid='' else status=$? child_pid='' printf 'Evaluation failed at epoch=%s; status=%s\n' "$epoch" "$status" >&2 exit "$status" fidone所有原评估参数均保留:--type evaluate、--cfg_file configs/linemod.yaml、test.dataset LinemodOccTest、model mycleanduck 和 cls_type duck。原来的 python 调用明确为 Python 3;实际使用时,仍须确认这个解释器属于已配置好 PVNet 依赖的环境。
脚本先拒绝覆盖已有 mycleanduck.log,然后备份配置的完整字节。配置匹配失败、评估返回非零或正常结束,都通过 EXIT trap 恢复。INT/TERM 路径先向记录的直接子进程发送 TERM 并等待,再退出恢复;日志同时保留标准输出与标准错误。Bash trap 与等待信号
这是单个调用进程的控制示例,不是完整的训练进程管理器。若真实程序忽略 TERM,等待可能延长;若它另建工作进程或进程组,需按框架的停止协议处理。SIGKILL、断电或存储故障不会执行 trap;恢复失败时保留备份路径,不能宣称任何情况下都能自动恢复。
本次只在自建的 run.py 测试替身中检查 epoch、参数、失败和信号路径,以及配置逐字节恢复;没有加载 PVNet 模型、数据集或进行真实评估。
整理 lm/olm:先拒绝碰撞,再移动和归档
跳转到“整理 lm/olm:先拒绝碰撞,再移动和归档”原流程是读入 name,把 lm 与 olm 移到同名目录,生成 name.zip,然后新建空的 lm/olm。原 echo "Create $naem file" 中的 naem 是拼写错误;read -r、变量引用和每一步失败检查也需要补上。
下面的脚本接收一个专用工作目录,交互读取单层归档名称。名称必须以字母或数字开头,其余只允许字母、数字、点、下划线、空格和连字符;不能是 lm 或 olm,也不能包含目录分隔符。运行期间不要让其他程序写入这些目录。
原 zip $name.zip $name -r 的用途是递归归档。这里使用 Python 标准库生成相同用途的 ZIP,避免依赖额外的 zip 命令;它是真实 ZIP 写入,不是对 Info-ZIP 的调用。若需要保留 Unix 特殊文件属性,应另外核对归档工具的能力,本例只接受普通文件与目录。
#!/usr/bin/env bashset -euo pipefailworkspace=${1:?Usage: bash archive-lm-olm.sh WORKSPACE}cd -- "$workspace"printf 'Input filename: 'IFS= read -r nameif [[ ! "$name" =~ ^[A-Za-z0-9][A-Za-z0-9._\ -]*$ || "$name" == lm || "$name" == olm ]]; then printf 'Use a new single-component archive name.\n' >&2 exit 1fifor destination in "$name" "$name.zip"; do if [[ -e "$destination" || -L "$destination" ]]; then printf 'Destination already exists: %s\n' "$destination" >&2 exit 1 fidonefor source in lm olm; do if [[ ! -d "$source" || -L "$source" ]]; then printf 'Expected an ordinary source directory: %s\n' "$source" >&2 exit 1 fidonecommand -v python3 >/dev/nullmkdir -- "$name"printf 'Moving lm and olm into %s\n' "$name"if ! mv -- lm "$name/lm"; then printf 'Move failed; inspect lm and %s\n' "$name" >&2 exit 1fiif ! mv -- olm "$name/olm"; then printf 'Move failed; lm is in %s/lm; inspect olm before retrying.\n' "$name" >&2 exit 1fiif ! python3 - "$name" "$name.zip" <<'PY'import pathlibimport sysimport zipfile
root = pathlib.Path(sys.argv[1])paths = [root, *sorted(root.rglob('*'))]for item in paths: if item.is_symlink() or not (item.is_dir() or item.is_file()): raise SystemExit(f'Unsupported entry: {item}')with zipfile.ZipFile(sys.argv[2], 'x', compression=zipfile.ZIP_DEFLATED) as archive: for item in paths: archive.write(item, arcname=item.as_posix())PYthen printf 'Archive failed; original data remains in %s. Inspect any partial ZIP.\n' "$name" >&2 exit 1fimkdir -- lm olmprintf 'Created %s.zip and fresh lm/olm directories.\n' "$name"成功后,原文件位于 name/lm 与 name/olm,ZIP 内保留这个目录层次,当前目录出现新的空 lm 与 olm。脚本不删除打包后的目录。
失败并不表示已经回到开始前的布局。第二次移动失败时,第一个目录可能已搬过去;归档失败时,两份数据仍在新目录中,还可能留下不完整 ZIP;最后创建空目录失败时,归档和原数据也保留。根据报错检查这些位置,再处理重试,不要直接运行覆盖或删除命令。
命令替换与变量读取
跳转到“命令替换与变量读取”$(command) 执行命令并捕获输出,$current_dir 则读取已经保存的变量。下面保留原来的 current_dir=$(pwd),再引用变量输出:
#!/usr/bin/env bashcurrent_dir=$(pwd)printf 'saved directory=%s\n' "$current_dir"赋值的等号两侧不能加空格。路径可能含空格,使用变量作为参数时应写成 "$current_dir"。命令替换会去掉输出末尾的换行;如果只是需要 Shell 已记录的当前目录,$PWD 也可直接读取。