chore(tools): 新增打印/PDF/表格工具与 OA→ERP 单点登录脚本
- tools/printer_probe.py:打印机协议非破坏性探测(端口/IPP 能力/LPD 队列,绝不提交作业) - tools/printer_client.py:IPP 直连打印(info / validate 干跑 / print 需显式 --yes) - tools/doc2pdf.py:网页 / HTML / Excel 指定区域转 PDF,产物可直接交给 printer_client - tools/sheet_print.py:Excel·WPS 表格按列过滤排版后分页打印 - tools/xq0012_payapply_pdf.py:XQ0012 套打 PDF 本地预览工具 - workflows/share/erp_sso_login.py:读 OA 登录态换 ERP 会话(新版/旧版,纯接口无浏览器) - workflows/README.md 新增 4.9 节说明
This commit is contained in:
@@ -0,0 +1,491 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""EPSON 网络打印机直连打印客户端(IPP over TLS)。
|
||||
|
||||
设计目标
|
||||
--------
|
||||
不依赖 Windows 打印队列 / 厂商驱动,直接按 IPP (RFC 8010/8011) 与打印机通信。
|
||||
本机实测设备:EPSON L6570 Series @ 172.30.40.254
|
||||
|
||||
安全默认
|
||||
--------
|
||||
`python tools/printer_client.py info` 读取设备能力(只读,绝不打印)
|
||||
`python tools/printer_client.py validate` 提交 Validate-Job(协议规定的"只校验不打印"操作)
|
||||
`python tools/printer_client.py print` 真正打印,必须显式加 --yes 才会执行
|
||||
|
||||
协议要点(逆向实测结论)
|
||||
------------------------
|
||||
1. 631 端口同时提供 IPP 与 IPPS;直接明文 POST 会被 426 Upgrade Required 拒绝,
|
||||
必须走 TLS(设备自签证书,测试期不校验证书)。
|
||||
2. 设备支持 document-format: application/octet-stream / image/pwg-raster /
|
||||
image/urf / image/jpeg / application/vnd.epson.escpr。
|
||||
3. 支持 Validate-Job(0x0004),可实现"校验通过但不出纸"的联调。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import socket
|
||||
import ssl
|
||||
import struct
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
DEFAULT_IP = "172.30.40.254"
|
||||
IPP_PORT = 631
|
||||
|
||||
# IPP 操作码
|
||||
OP_PRINT_JOB = 0x0002
|
||||
OP_VALIDATE_JOB = 0x0004
|
||||
OP_CREATE_JOB = 0x0005
|
||||
OP_GET_JOBS = 0x000A
|
||||
OP_GET_PRINTER_ATTRIBUTES = 0x000B
|
||||
|
||||
STATUS_TEXT = {
|
||||
0x0000: "successful-ok",
|
||||
0x0001: "successful-ok-ignored-or-substituted-attributes",
|
||||
0x0002: "successful-ok-conflicting-attributes",
|
||||
0x0400: "client-error-bad-request",
|
||||
0x0401: "client-error-forbidden",
|
||||
0x0403: "client-error-not-found",
|
||||
0x0404: "client-error-not-possible",
|
||||
0x0405: "client-error-timeout",
|
||||
0x0406: "client-error-not-found(?)",
|
||||
0x040B: "client-error-document-format-not-supported",
|
||||
0x040A: "client-error-attributes-or-values-not-supported",
|
||||
0x0500: "server-error-internal-error",
|
||||
0x0502: "server-error-service-unavailable",
|
||||
}
|
||||
|
||||
# IPP 值标签
|
||||
T_OPERATION = 0x01
|
||||
T_JOB = 0x02
|
||||
T_END = 0x03
|
||||
T_INTEGER = 0x21
|
||||
T_BOOLEAN = 0x22
|
||||
T_ENUM = 0x23
|
||||
T_STRING = 0x30
|
||||
T_NAME = 0x42
|
||||
T_KEYWORD = 0x44
|
||||
T_URI = 0x45
|
||||
T_CHARSET = 0x47
|
||||
T_LANGUAGE = 0x48
|
||||
T_MIME = 0x49
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# IPP 报文构造/解析
|
||||
# --------------------------------------------------------------------------- #
|
||||
def attr(tag: int, name: bytes | str, value: bytes | str | int) -> bytes:
|
||||
"""构造一个 IPP 属性三元组 (value-tag, name-length+name, value-length+value)。"""
|
||||
nb = name.encode() if isinstance(name, str) else name
|
||||
if isinstance(value, int):
|
||||
vb, tag = struct.pack(">i", value), T_INTEGER
|
||||
elif isinstance(value, str):
|
||||
vb = value.encode("utf-8")
|
||||
else:
|
||||
vb = value
|
||||
return bytes([tag]) + struct.pack(">H", len(nb)) + nb + struct.pack(">H", len(vb)) + vb
|
||||
|
||||
|
||||
def build_request(op: int, uri: str, operation_attrs: list[bytes],
|
||||
job_attrs: list[bytes] | None = None, req_id: int = 1) -> bytes:
|
||||
body = bytes([T_OPERATION])
|
||||
body += attr(T_CHARSET, b"attributes-charset", b"utf-8")
|
||||
body += attr(T_LANGUAGE, b"attributes-natural-language", b"en-us")
|
||||
body += attr(T_URI, b"printer-uri", uri.encode())
|
||||
body += attr(T_NAME, b"requesting-user-name", b"37du-auto")
|
||||
for a in operation_attrs:
|
||||
body += a
|
||||
if job_attrs:
|
||||
body += bytes([T_JOB])
|
||||
for a in job_attrs:
|
||||
body += a
|
||||
body += bytes([T_END])
|
||||
return struct.pack(">BBHI", 2, 0, op, req_id) + body
|
||||
|
||||
|
||||
def parse_attributes(payload: bytes) -> tuple[int, dict]:
|
||||
"""解析 IPP 响应体,返回 (状态码, 属性字典)。"""
|
||||
if len(payload) < 8:
|
||||
return -1, {}
|
||||
status = struct.unpack(">H", payload[2:4])[0]
|
||||
attrs: dict[str, list] = {}
|
||||
i, cur = 8, None
|
||||
while i < len(payload):
|
||||
tag = payload[i]
|
||||
if tag == T_END:
|
||||
break
|
||||
if tag < 0x10:
|
||||
i += 1
|
||||
continue
|
||||
if i + 3 > len(payload):
|
||||
break
|
||||
nl = struct.unpack(">H", payload[i + 1:i + 3])[0]
|
||||
name = payload[i + 3:i + 3 + nl].decode("utf-8", "replace")
|
||||
i += 3 + nl
|
||||
if i + 2 > len(payload):
|
||||
break
|
||||
vl = struct.unpack(">H", payload[i:i + 2])[0]
|
||||
raw = payload[i + 2:i + 2 + vl]
|
||||
i += 2 + vl
|
||||
if name:
|
||||
cur = name
|
||||
attrs.setdefault(cur or "?", []).append((tag, raw))
|
||||
return status, attrs
|
||||
|
||||
|
||||
def _val(tag: int, raw: bytes):
|
||||
if tag in (T_INTEGER, T_ENUM):
|
||||
return int.from_bytes(raw, "big", signed=(tag == T_INTEGER))
|
||||
if tag == T_BOOLEAN:
|
||||
return bool(raw and raw[0])
|
||||
if tag == 0x33: # rangeOfInteger
|
||||
return raw.hex(" ")
|
||||
return raw.decode("utf-8", "replace")
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 传输层
|
||||
# --------------------------------------------------------------------------- #
|
||||
class PrinterClient:
|
||||
def __init__(self, ip: str = DEFAULT_IP, port: int = IPP_PORT,
|
||||
path: str = "/ipp/print", timeout: float = 30.0,
|
||||
tls: bool = True):
|
||||
self.ip, self.port, self.path, self.timeout = ip, port, path, timeout
|
||||
self.tls = tls
|
||||
# IPv6 字面量在 URI / Host 头里必须加方括号(含 zone index 的链路本地地址也一样)
|
||||
host = f"[{ip}]" if ":" in ip else ip
|
||||
self.host_header = f"{host}:{port}"
|
||||
self.uri = f"{'ipps' if tls else 'ipp'}://{host}:{port}{path}"
|
||||
self._req_id = 0
|
||||
|
||||
def _connect(self) -> ssl.SSLSocket | socket.socket:
|
||||
sock = socket.create_connection((self.ip, self.port), timeout=self.timeout)
|
||||
if not self.tls:
|
||||
return sock
|
||||
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
|
||||
ctx.check_hostname = False
|
||||
ctx.verify_mode = ssl.CERT_NONE
|
||||
try:
|
||||
ctx.set_ciphers("DEFAULT:@SECLEVEL=1")
|
||||
except ssl.SSLError:
|
||||
pass
|
||||
# IP 字面量不做 SNI(含 %zone 的链路本地地址不是合法 SNI 名)
|
||||
return ctx.wrap_socket(sock, server_hostname=None)
|
||||
|
||||
def request(self, op: int, operation_attrs: list[bytes],
|
||||
job_attrs: list[bytes] | None = None,
|
||||
document: bytes = b"",
|
||||
document_format: str | None = None) -> tuple[int, dict, bytes]:
|
||||
self._req_id += 1
|
||||
ops = list(operation_attrs)
|
||||
if document_format:
|
||||
ops.append(attr(T_MIME, b"document-format", document_format.encode()))
|
||||
body = build_request(op, self.uri, ops, job_attrs, self._req_id)
|
||||
head = (
|
||||
f"POST {self.path} HTTP/1.1\r\n"
|
||||
f"Host: {self.host_header}\r\n"
|
||||
"Content-Type: application/ipp\r\n"
|
||||
f"Content-Length: {len(body) + len(document)}\r\n"
|
||||
"Connection: close\r\n\r\n"
|
||||
).encode()
|
||||
s = self._connect()
|
||||
try:
|
||||
s.sendall(head + body + document)
|
||||
data = b""
|
||||
while True:
|
||||
try:
|
||||
chunk = s.recv(65536)
|
||||
except (socket.timeout, ssl.SSLError):
|
||||
break
|
||||
if not chunk:
|
||||
break
|
||||
data += chunk
|
||||
finally:
|
||||
s.close()
|
||||
http_head, _, payload = data.partition(b"\r\n\r\n")
|
||||
http_code = 0
|
||||
for tok in http_head.split(b"\r\n", 1)[0].split():
|
||||
if tok.isdigit():
|
||||
http_code = int(tok)
|
||||
status, attrs = parse_attributes(payload)
|
||||
return (status if status >= 0 else http_code), attrs, data
|
||||
|
||||
# --- 能力探测与参数降级 ---
|
||||
def caps(self) -> dict:
|
||||
"""缓存设备能力属性(首次调用走一次 Get-Printer-Attributes)。"""
|
||||
if getattr(self, "_caps", None) is None:
|
||||
self._caps = self.get_attributes()["attrs"]
|
||||
return self._caps
|
||||
|
||||
def check_options(self, opts: dict) -> dict:
|
||||
"""提前剔除设备不支持的参数。
|
||||
|
||||
EPSON 这两台即使带 ipp-attribute-fidelity=true 也**不报错**,
|
||||
只会静默忽略(实测),所以必须在客户端侧先判断,避免"以为打了双面"。
|
||||
"""
|
||||
c = self.caps()
|
||||
warn = []
|
||||
if opts.get("sides") and "sides-supported" in c and opts["sides"] not in c["sides-supported"]:
|
||||
warn.append(f"不支持 sides={opts['sides']}(支持 {c['sides-supported']}),已改为单面")
|
||||
opts["sides"] = None
|
||||
if opts.get("media") and "media-supported" in c and opts["media"] not in c["media-supported"]:
|
||||
warn.append(f"不支持 media={opts['media']},已改用默认 {c.get('media-default')}")
|
||||
opts["media"] = None
|
||||
if opts.get("color") and "print-color-mode-supported" in c \
|
||||
and opts["color"] not in c["print-color-mode-supported"]:
|
||||
warn.append(f"不支持 color={opts['color']},已改用默认")
|
||||
opts["color"] = None
|
||||
for w in warn:
|
||||
print(f"[warn] {w}")
|
||||
return opts
|
||||
|
||||
# --- 高层操作 ---
|
||||
def get_attributes(self, wanted: list[str] | None = None) -> dict:
|
||||
ops = [attr(T_KEYWORD, b"requested-attributes", w.encode())
|
||||
for w in (wanted or ["all"])]
|
||||
status, attrs, _ = self.request(OP_GET_PRINTER_ATTRIBUTES, ops)
|
||||
flat = {k: [_val(t, v) for t, v in vv] for k, vv in attrs.items()}
|
||||
return {"status": STATUS_TEXT.get(status, hex(status)), "attrs": flat}
|
||||
|
||||
def validate_job(self, document: bytes, doc_format: str,
|
||||
job_name: str = "37du-validate", **opts) -> dict:
|
||||
"""Validate-Job:协议层校验作业是否可被接受,设备不得打印。"""
|
||||
opts = self.check_options(dict(opts))
|
||||
job_attrs = [attr(T_NAME, b"job-name", job_name.encode())]
|
||||
job_attrs += _job_options(**opts)
|
||||
status, attrs, raw = self.request(
|
||||
OP_VALIDATE_JOB, [], job_attrs, document=document, document_format=doc_format)
|
||||
flat = {k: [_val(t, v) for t, v in vv] for k, vv in attrs.items()}
|
||||
return {"status": STATUS_TEXT.get(status, hex(status)),
|
||||
"status_code": status, "attrs": flat, "bytes": len(raw)}
|
||||
|
||||
def print_job(self, document: bytes, doc_format: str,
|
||||
job_name: str = "37du-print", **opts) -> dict:
|
||||
"""Print-Job:真正打印作业。"""
|
||||
opts = self.check_options(dict(opts))
|
||||
job_attrs = [attr(T_NAME, b"job-name", job_name.encode())]
|
||||
job_attrs += _job_options(**opts)
|
||||
status, attrs, raw = self.request(
|
||||
OP_PRINT_JOB, [], job_attrs, document=document, document_format=doc_format)
|
||||
flat = {k: [_val(t, v) for t, v in vv] for k, vv in attrs.items()}
|
||||
return {"status": STATUS_TEXT.get(status, hex(status)),
|
||||
"status_code": status, "attrs": flat, "bytes": len(raw)}
|
||||
|
||||
def get_jobs(self, which: str = "completed", limit: int = 10) -> dict:
|
||||
ops = [attr(T_KEYWORD, b"which-jobs", which.encode()),
|
||||
attr(T_INTEGER, b"limit", limit)]
|
||||
status, attrs, _ = self.request(OP_GET_JOBS, ops)
|
||||
return {"status": STATUS_TEXT.get(status, hex(status)),
|
||||
"attrs": {k: [_val(t, v) for t, v in vv] for k, vv in attrs.items()}}
|
||||
|
||||
|
||||
def _job_options(media: str | None = None, copies: int | None = None,
|
||||
sides: str | None = None, color: str | None = None,
|
||||
quality: int | None = None, scaling: str | None = None,
|
||||
resolution: tuple[int, int] | None = None) -> list[bytes]:
|
||||
out: list[bytes] = []
|
||||
if media:
|
||||
out.append(attr(T_KEYWORD, b"media", media.encode()))
|
||||
if copies:
|
||||
out.append(attr(T_INTEGER, b"copies", copies))
|
||||
if sides:
|
||||
out.append(attr(T_KEYWORD, b"sides", sides.encode()))
|
||||
if color:
|
||||
out.append(attr(T_KEYWORD, b"print-color-mode", color.encode()))
|
||||
if quality:
|
||||
out.append(attr(T_INTEGER, b"print-quality", quality))
|
||||
if scaling:
|
||||
out.append(attr(T_KEYWORD, b"print-scaling", scaling.encode()))
|
||||
if resolution:
|
||||
out.append(attr(T_INTEGER, b"printer-resolution", resolution[0]))
|
||||
return out
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 测试载荷生成
|
||||
# --------------------------------------------------------------------------- #
|
||||
def make_jpeg(text: str = "37du test", size: tuple[int, int] = (600, 300)) -> bytes:
|
||||
"""生成一张测试图(不落盘),仅用于 Validate-Job 探测格式兼容性。"""
|
||||
from io import BytesIO
|
||||
|
||||
from PIL import Image, ImageDraw
|
||||
img = Image.new("RGB", size, "white")
|
||||
d = ImageDraw.Draw(img)
|
||||
d.rectangle([4, 4, size[0] - 5, size[1] - 5], outline="black", width=3)
|
||||
d.text((24, size[1] // 2 - 8), text, fill="black")
|
||||
buf = BytesIO()
|
||||
img.save(buf, "JPEG", quality=90)
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def make_escpr_stub() -> bytes:
|
||||
"""最小 ESC/P-R 起始序列(仅用于格式协商测试,不含页面数据,不会成像)。"""
|
||||
return (b"\x1b@\x1b(G\x00\x01\x00\x00\x01" # ESC @ 复位 + ESC ( G 图形模式
|
||||
b"\x1b\x01@EJL 1284.4\n@EJL \n") # Epson EJL 作业语言头
|
||||
|
||||
|
||||
def render_pages(src: Path, dpi: int = 300, quality: int = 92) -> list[bytes]:
|
||||
"""把 PDF / 图片渲染成逐页 JPEG 字节流。
|
||||
|
||||
设备 document-format 支持 image/jpeg(Mopria 2.0 认证),因此
|
||||
任意文档 = 先栅格化再逐页提交,无需厂商驱动、无需 ESC/P-R 编码器。
|
||||
"""
|
||||
from io import BytesIO
|
||||
|
||||
from PIL import Image
|
||||
|
||||
pages: list[bytes] = []
|
||||
if src.suffix.lower() == ".pdf":
|
||||
import pypdfium2 as pdfium
|
||||
pdf = pdfium.PdfDocument(str(src))
|
||||
scale = dpi / 72.0
|
||||
for i in range(len(pdf)):
|
||||
bitmap = pdf[i].render(scale=scale, rotation=0)
|
||||
img = bitmap.to_pil().convert("RGB")
|
||||
buf = BytesIO()
|
||||
img.save(buf, "JPEG", quality=quality, dpi=(dpi, dpi))
|
||||
pages.append(buf.getvalue())
|
||||
img.close()
|
||||
pdf.close()
|
||||
else:
|
||||
img = Image.open(src).convert("RGB")
|
||||
buf = BytesIO()
|
||||
img.save(buf, "JPEG", quality=quality, dpi=(dpi, dpi))
|
||||
pages.append(buf.getvalue())
|
||||
img.close()
|
||||
return pages
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# CLI
|
||||
# --------------------------------------------------------------------------- #
|
||||
def _resolve_payload(args) -> tuple[list[tuple[bytes, str]], str]:
|
||||
"""返回 [(载荷, mime), ...];一个元素=一个 IPP 作业。"""
|
||||
if args.input:
|
||||
pages = render_pages(Path(args.input), dpi=args.dpi)
|
||||
return [(p, "image/jpeg") for p in pages], f"渲染 {len(pages)} 页 @ {args.dpi}dpi"
|
||||
if args.file:
|
||||
p = Path(args.file)
|
||||
mime = {"jpeg": "image/jpeg", "escpr": "application/vnd.epson.escpr",
|
||||
"pwg": "image/pwg-raster"}[args.fmt]
|
||||
return [(p.read_bytes(), mime)], f"读取 {p.name} ({p.stat().st_size}B)"
|
||||
if args.fmt == "jpeg":
|
||||
return [(make_jpeg(), "image/jpeg")], "内置测试图"
|
||||
return [(make_escpr_stub(), "application/vnd.epson.escpr"
|
||||
if args.fmt == "escpr" else "image/pwg-raster")], "内置最小载荷"
|
||||
|
||||
|
||||
def cmd_info(c: PrinterClient) -> int:
|
||||
r = c.get_attributes()
|
||||
a = r["attrs"]
|
||||
print(f"IPP 状态 : {r['status']}")
|
||||
for k in ("printer-make-and-model", "printer-name", "printer-state",
|
||||
"printer-state-reasons", "printer-is-accepting-jobs",
|
||||
"document-format-supported", "document-format-default",
|
||||
"media-default", "sides-supported", "print-color-mode-supported",
|
||||
"printer-device-id", "printer-firmware-string-version", "pages-per-minute",
|
||||
"mopria-certified", "queued-job-count"):
|
||||
if k in a:
|
||||
print(f"{k:<30}: {a[k]}")
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_validate(c: PrinterClient, args) -> int:
|
||||
payloads, note = _resolve_payload(args)
|
||||
doc, mime = payloads[0]
|
||||
print(f"载荷: {note}")
|
||||
r = c.validate_job(doc, mime, job_name=f"37du-validate-{args.fmt}",
|
||||
media=args.media, sides=args.sides, color=args.color)
|
||||
print(f"Validate-Job [{mime}] -> {r['status']} (0x{r['status_code']:04X})"
|
||||
f",载荷 {len(doc)}B")
|
||||
for k, v in r["attrs"].items():
|
||||
if k in ("status-message", "job-state-reasons", "document-format-supported"):
|
||||
print(f" {k} = {v}")
|
||||
ok = r["status_code"] < 0x0100
|
||||
print("结论: 设备接受该作业参数与格式(Device did NOT print)" if ok
|
||||
else "结论: 设备拒绝该作业")
|
||||
return 0 if ok else 2
|
||||
|
||||
|
||||
def cmd_print(c: PrinterClient, args) -> int:
|
||||
payloads, note = _resolve_payload(args)
|
||||
print(f"载荷: {note},共 {len(payloads)} 个作业")
|
||||
if not args.yes:
|
||||
for i, (doc, mime) in enumerate(payloads, 1):
|
||||
print(f" [干跑] 作业{i}: {mime} {len(doc)}B "
|
||||
f"MD5={__import__('hashlib').md5(doc).hexdigest()[:16]}")
|
||||
print("拒绝执行:真正打印必须显式加 --yes。已完成干跑,未向设备发送任何作业。")
|
||||
return 3
|
||||
rc = 0
|
||||
for i, (doc, mime) in enumerate(payloads, 1):
|
||||
r = c.print_job(doc, mime, job_name=f"37du-{i}",
|
||||
media=args.media, sides=args.sides, color=args.color)
|
||||
print(f" Print-Job 页{i} -> {r['status']}")
|
||||
if r["status_code"] >= 0x0100:
|
||||
rc = 2
|
||||
print(" " + json.dumps(r["attrs"], ensure_ascii=False))
|
||||
return rc
|
||||
|
||||
|
||||
def cmd_render(args) -> int:
|
||||
"""只做栅格化,把将要发给打印机的字节落盘,便于离线检查。"""
|
||||
pages = render_pages(Path(args.input), dpi=args.dpi)
|
||||
out = Path(args.out)
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
for i, p in enumerate(pages, 1):
|
||||
f = out / f"page-{i:03d}.jpg"
|
||||
f.write_bytes(p)
|
||||
print(f" {f} {len(p)}B ({len(p)/1024:.1f} KB)")
|
||||
print(f"共 {len(pages)} 页,未连接打印机。")
|
||||
return 0
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser(description="EPSON IPP 直连打印客户端")
|
||||
ap.add_argument("action", choices=["info", "validate", "print", "render", "jobs"])
|
||||
ap.add_argument("--ip", default=DEFAULT_IP)
|
||||
ap.add_argument("--port", type=int, default=IPP_PORT)
|
||||
ap.add_argument("--path", default="/ipp/print")
|
||||
ap.add_argument("--fmt", default="jpeg", choices=["jpeg", "escpr", "pwg"])
|
||||
ap.add_argument("--input", help="源文档 pdf/png/jpg,自动栅格化为 JPEG")
|
||||
ap.add_argument("--file", help="现成载荷文件(配合 --fmt 指定 mime)")
|
||||
ap.add_argument("--out", default="tools/out", help="render 输出目录")
|
||||
ap.add_argument("--dpi", type=int, default=300)
|
||||
ap.add_argument("--media", default=None, help="如 iso_a4_210x297mm")
|
||||
ap.add_argument("--sides", default=None,
|
||||
choices=["one-sided", "two-sided-long-edge", "two-sided-short-edge"])
|
||||
ap.add_argument("--color", default=None,
|
||||
choices=["color", "monochrome", "auto"])
|
||||
ap.add_argument("--yes", action="store_true", help="确认真正打印")
|
||||
ap.add_argument("--no-tls", action="store_true", help="明文 IPP(本机实测会被 426 拒绝)")
|
||||
args = ap.parse_args()
|
||||
|
||||
if args.action == "render":
|
||||
if not args.input:
|
||||
print("render 需要 --input", file=sys.stderr)
|
||||
return 1
|
||||
return cmd_render(args)
|
||||
|
||||
c = PrinterClient(args.ip, args.port, args.path, tls=not args.no_tls)
|
||||
print(f"目标: {c.uri}")
|
||||
try:
|
||||
if args.action == "info":
|
||||
return cmd_info(c)
|
||||
if args.action == "validate":
|
||||
return cmd_validate(c, args)
|
||||
if args.action == "print":
|
||||
return cmd_print(c, args)
|
||||
if args.action == "jobs":
|
||||
print(json.dumps(c.get_jobs(), ensure_ascii=False, indent=1))
|
||||
return 0
|
||||
except (socket.error, ssl.SSLError, OSError) as e:
|
||||
print(f"通信失败: {type(e).__name__}: {e}", file=sys.stderr)
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in New Issue
Block a user