JSON 输出与自动化
CLI 可以在本机按顺序串联采集、图像处理和 OCR。脚本应读取命令返回的实际文件路径,不依赖终端提示或预测文件名。先手动完成安装与授权,确认设备可用,再自动化业务步骤。
输出与退出码
需要机器可读结果时使用 --json,分别捕获 stdout 和 stderr,不要合并两条流。正常的 JSON 结果写入 stdout;诊断、下载进度与更新提示写入 stderr。账号登录在 JSON 模式下将浏览器授权链接写入 stderr,最终结果写入 stdout。
不加 --json 时,许多操作提示写入 stderr;version 的版本号、ocr extract-text 的纯文本以及普通登录模式的授权链接则写入 stdout。因此不要用“stdout 非空”判断所有命令是否成功。
处理结果的推荐顺序:
- 等待命令退出,保留 stderr 便于诊断。
- 退出码非零时停止,不继续启动 OCR 或其他有副作用的步骤。
- 退出码为零时再解析预期的 JSON,并按该命令的字段判断业务结果。
- 检查产物列表和文件是否存在,再把真实路径交给下一步。
参数或配置失败时,即使传入 --json,也可能仅有 stderr 而没有 JSON;错误的 error 字段可能是字符串或对象。不要假设所有命令具有统一的错误对象或 status 字段。
| 情况 | 如何判断 |
|---|---|
| 扫描、基础图像处理、增强、OCR | 退出码为 0,并检查 status: "succeeded" 与所需结果 |
doctor | 健康为 0,不健康为 1,参数或配置错误为 2 |
auth status | 本地已登录为 0,未登录为 1,读取等错误为 2;不验证远程有效性 |
auth logout | 远程撤销未确认可返回 1,即使本地状态已清除 |
runtime check-updates | unknown、unsupported 也可返回 0,仍需读取状态 |
| 其他非零退出 | 停止并检查诊断;不要将 2 一概解释为参数错误,授权失败也可能返回 2 |
读取正确的路径字段
| 命令 | 结果字段 |
|---|---|
scan | files[].path,另有 content_type、size;可能返回多张图片 |
image process / process-page / apply-color-mode | 单个 output_path,另有 input_path、operation、content_type、size |
image enhance / ocr recognize | files[].path、file_uri、content_type、size,以及 task_id、进度等 |
ocr extract-text | text、recognized、blocks 等;不生成图片或文档路径 |
CLI 的本地路径不是 MCP 的 local_path。文件可能因处理模式产生多个结果,务必保持返回数组的顺序。空文字是有效提取结果,但需要文档产物的流程不能把空文件列表当成功交付。
跨平台 Python 示例
下面的脚本完成“一次扫描 → 读取返回图片 → OCR 导出 PDF”。Python 3 只用于这个自动化示例,不是安装 CLI 的前置依赖。仅使用 Python 标准库,不经过 shell,不在脚本或命令参数中写 Key;子进程继承当前环境的账号或 CZUR_OPEN_API_KEY 配置。
将代码保存为 scan_to_pdf.py:
from pathlib import Path
import argparse
import json
import shutil
import subprocess
import sys
def cli_command(cli_entry=None):
if cli_entry:
entry = Path(cli_entry).expanduser().resolve()
node = shutil.which("node")
if not entry.is_file() or not node:
raise RuntimeError("Provide an existing CLI dist/bin.js and install Node.js.")
return [node, str(entry)]
executable = shutil.which("czur-open")
if not executable:
raise RuntimeError("czur-open is not on PATH. Install the CLI first.")
if Path(executable).suffix.lower() in (".cmd", ".bat"):
entry = Path(executable).parent / "node_modules/@czur/open-cli/dist/bin.js"
if not entry.is_file():
raise RuntimeError("Locate dist/bin.js with npm root -g and pass --cli-entry.")
return cli_command(str(entry))
return [executable]
def run_json(cli, arguments):
result = subprocess.run(
[*cli, *arguments, "--json"],
capture_output=True,
text=True,
encoding="utf-8",
check=False,
)
if result.stderr:
print(result.stderr, file=sys.stderr, end="")
if result.returncode != 0:
raise RuntimeError(f"CLI exited with code {result.returncode}; stopping.")
try:
data = json.loads(result.stdout)
except json.JSONDecodeError as error:
raise RuntimeError("CLI did not return valid JSON; stopping.") from error
if not isinstance(data, dict) or data.get("status") != "succeeded":
raise RuntimeError("CLI did not report status=succeeded; stopping.")
return data
def delivered_files(data, images_only=False):
files = data.get("files")
if not isinstance(files, list) or not files:
raise RuntimeError("No delivered files; stopping.")
paths = []
for item in files:
if not isinstance(item, dict) or not isinstance(item.get("path"), str):
raise RuntimeError("Invalid delivered file metadata; stopping.")
if images_only and not str(item.get("content_type", "")).startswith("image/"):
raise RuntimeError("Scan returned a non-image file; stopping.")
path = Path(item["path"])
if not item["path"] or not path.is_file():
raise RuntimeError("A delivered file is missing; stopping.")
paths.append(str(path))
return paths
def main(argv=None):
parser = argparse.ArgumentParser(description="Scan one document and export an OCR PDF.")
parser.add_argument("device_id")
parser.add_argument("--output-root", default="./czur-results")
parser.add_argument("--task-timeout", type=int, default=300000)
parser.add_argument("--cli-entry", help="Optional absolute path to @czur/open-cli/dist/bin.js")
args = parser.parse_args(argv)
if args.task_timeout <= 0:
parser.error("--task-timeout must be positive")
cli = cli_command(args.cli_entry)
root = Path(args.output_root).expanduser().resolve()
scan = run_json(cli, [
"scan", args.device_id,
"--count", "1",
"--page-processing", "single_page",
"--color-mode", "auto_optimize",
"--format", "jpg",
"--output-dir", str(root / "scans"),
])
images = delivered_files(scan, images_only=True)
document = run_json(cli, [
"ocr", "recognize", *images,
"--format", "pdf",
"--export-type", "multi-page",
"--task-timeout", str(args.task_timeout),
"--output-dir", str(root / "documents"),
])
for path in delivered_files(document):
print(path)
return 0
if __name__ == "__main__":
try:
sys.exit(main())
except (OSError, RuntimeError) as error:
print(f"Error: {error}", file=sys.stderr)
sys.exit(1)从设备列表复制实际 ID 后运行;脚本会立即采集一张,请先放好文档:
czur-open device list --json
python scan_to_pdf.py "YOUR_DEVICE_ID" --output-root "./My Documents/CZUR" --task-timeout 600000如果系统命令名是 python3,将 python 替换为 python3。Windows 的 npm .cmd / .bat 入口会优先转换为相邻安装目录下的 Node.js 入口,避免通过 shell 执行命令。若自动定位失败,先查询全局包目录:
npm root -g在该目录下找到 @czur/open-cli/dist/bin.js,使用其真实路径:
python scan_to_pdf.py "YOUR_DEVICE_ID" --cli-entry "/ABSOLUTE/PATH/TO/@czur/open-cli/dist/bin.js" --output-root "./My Documents/CZUR"--cli-entry 是本示例脚本的参数,不是 czur-open 的参数;在 Windows 上请替换为对应的盘符路径。脚本将输出 OCR 文档的真实路径,扫描图片保留在 scans 子目录,文档保留在 documents 子目录。
超时、重试与数据安全
脚本不额外设置会强行杀死 CLI 的 subprocess 超时。使用 CLI 的 --task-timeout 控制增强或 OCR 长任务的等待;默认 300000 毫秒。--timeout 是单次 Runtime 请求超时,扫描等待由 --capture-timeout 控制,不能相互替代。
每次 CLI 长任务在同一进程与连接中提交、等待和下载,不提供跨进程的任务恢复。中断或超时只尝试官方支持的取消,不能保证计算立即停止。断线、失败或交付异常后不要盲目重新提交;先检查已下载产物和诊断,避免重复扫描或处理。
先后执行步骤,不让多个脚本争用同一设备。多页人工翻页时,逐次运行单页扫描并等待人工确认;scan --count 不会暂停等待翻页。需要 AI 分析时,单独决定是否将产物发送到相应服务,见隐私与安全。完整的格式和选项见命令参考及 OCR 与文档导出。