JSON output and automation
Use the CLI to sequence capture, image processing, and OCR on your computer. Read actual file paths from command results instead of parsing terminal messages or predicting filenames. Complete installation and authorization manually and confirm device availability before automating your workflow.
Output and exit codes
Use --json for machine-readable results and capture stdout and stderr separately. Do not merge the streams. Normal JSON results go to stdout; diagnostics, download progress, and update notices go to stderr. In JSON mode, account login prints its browser authorization link to stderr and its final result to stdout.
Without --json, many operational messages go to stderr. However, the version number, plain text from ocr extract-text, and the authorization link in ordinary login mode go to stdout. Nonempty stdout is therefore not a universal success indicator.
Process results in this order:
- Wait for the command to exit and retain stderr for diagnostics.
- Stop on any nonzero exit code; do not launch OCR or other side-effecting steps.
- On exit code zero, parse the expected JSON and inspect command-specific fields.
- Check the delivered files and their existence before passing actual paths onward.
Argument or configuration failures may produce only stderr, even with --json. An error field may be a string or an object. Do not assume all commands share one error schema or even have a status field.
| Situation | Interpretation |
|---|---|
| Scan, basic image processing, enhancement, OCR | Require exit code 0, status: "succeeded", and the expected result |
doctor | 0 for healthy, 1 for unhealthy, 2 for argument or configuration errors |
auth status | 0 for locally signed in, 1 for signed out, 2 for errors such as unreadable state; does not validate remote authorization |
auth logout | May return 1 if remote revocation is unconfirmed, even after local state is cleared |
runtime check-updates | unknown and unsupported can also return 0; inspect the status |
| Other nonzero exits | Stop and inspect diagnostics; do not classify every 2 as an argument error, since authorization failures can also return 2 |
Read the correct path fields
| Command | Result fields |
|---|---|
scan | files[].path, plus content_type and size; may deliver multiple images |
image process / process-page / apply-color-mode | One output_path, plus input_path, operation, content_type, and size |
image enhance / ocr recognize | files[].path, file_uri, content_type, size, plus task_id, progress, and other fields |
ocr extract-text | text, recognized, blocks, and other recognition fields; no image or document path |
CLI paths are not the MCP local_path field. Processing modes may produce multiple files; preserve the returned array order. Empty text is a valid extraction result, but a workflow requiring document files must not treat an empty file list as successful delivery.
Cross-platform Python example
This script performs one scan, reads its returned images, and exports an OCR PDF. Python 3 is needed only for this automation example, not to install the CLI. The script uses only the Python standard library, does not invoke a shell, and keeps Keys out of source code and command arguments. Child processes inherit the current account or CZUR_OPEN_API_KEY environment configuration.
Save this as 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)Copy the actual ID from the device list, then run the script. Place the document first: capture begins immediately.
czur-open device list --json
python scan_to_pdf.py "YOUR_DEVICE_ID" --output-root "./My Documents/CZUR" --task-timeout 600000If your system uses python3, substitute it for python. For Windows npm .cmd / .bat shims, the script first resolves the adjacent installed Node.js entry to avoid invoking a shell. If automatic lookup fails, locate the global package directory:
npm root -gFind @czur/open-cli/dist/bin.js inside that directory and pass its actual path:
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 belongs to this example script, not to czur-open. On Windows, replace the example with the corresponding drive-letter path. The script prints the actual OCR document paths, retaining scanned images in the scans subdirectory and documents in documents.
Timeouts, retries, and data safety
The script does not add a subprocess timeout that would forcibly kill the CLI. Use CLI --task-timeout for enhancement or OCR task waiting; the default is 300000 milliseconds. --timeout controls a single Runtime request, while scan completion uses --capture-timeout. These settings are not interchangeable.
Each CLI long task submits, waits, and downloads within the same process and connection; cross-process task recovery is not provided. Interruption or timeout only attempts officially supported cancellation and does not guarantee immediate computation termination. Do not blindly resubmit after a disconnect, failure, or delivery error. Inspect existing files and diagnostics first to avoid duplicate capture or processing.
Run steps sequentially rather than letting scripts compete for one device. For manual page turning, run individual single-page scans with human confirmation between them; scan --count does not pause for page turns. Decide separately whether to send results to an AI service; see privacy and security. See Command Reference and OCR and document export for format and option details.