如何检测当前终端是否支持 Sixel?
解读
在国内一线互联网与科研单位,Matplotlib 常被要求“无窗口”输出到远程 SSH 终端、JupyterHub 容器或工业串口屏。Sixel 作为“像素级”位图内联协议,可直接把 Figure 以 \033Pq...\033\ 形式塞进终端,省掉 scp 再开图片查看器的流程。面试官问“如何检测”,核心想确认两点:
- 候选人是否知道 Sixel 是终端能力,不是 Python 能力;
- 能否给出可落地的跨平台方案,并解释为什么 Matplotlib 官方后端
mpl_backend_sixel至今未合入主分支。
回答若只抛echo $TERM或tput colors会被判“背题”;必须展示运行时探测 + 回退策略,并关联 Matplotlib 的后端注册机制。
知识点
- Sixel 协议格式:DCS 起始
ESC P q,调色板段#Pn;...,光栅属性"Pan;Pad;Ph;Pv,数据段#1;...,ST 终止ESC \。 - 终端能力数据库:termcap/terminfo 中无 Sixel 标准字段,需依赖私有扩展
Ss、Se或RGB、Tc。 - 环境变量陷阱:
TERM=xterm-256color的 99% 实现并不支持 Sixel;TERM=mlterm、xterm-sixel、wezterm、iTerm2才大概率支持。 - 运行时探测命令:
echo -e '\033[c'→ 解析返回的 DA1 响应,若 bit 4 (Sixel) 置位则支持;echo -e '\033[?1;1;0S'并读回\033[?1;0;0S确认无报错;- 直接写 1×1 透明 Sixel 后光标坐标是否漂移。
- Python 侧封装:用
pty+subprocess起子 shell,发探测序列,超时 200 ms 内若收到合法响应即判支持;封装为matplotlib.backends._sixel.detect(),供后端FigureCanvasSixel在print_figure()前调用。 - Matplotlib 后端注册:继承
FigureCanvasBase,实现print_sixel(io, *args, **kwargs),通过matplotlib.backend_registry.BackendFilter动态启用;若探测失败自动回退到agg+base64内联,或提示用户安装img2sixel。 - 国内常见终端实测矩阵:
- Windows 商店版 Windows Terminal 1.18+ 需手动开
experimental.sixel; - 统信 UOS 自带 deepin-terminal 基于 Qt5,不支持;
- 华为云 CloudShell 基于 hterm,不支持;
- 阿里 CloudTty 魔改 xterm.js,需后端开
sixel=1才支持。
因此任何硬编码白名单都不安全,必须运行时探测。
- Windows 商店版 Windows Terminal 1.18+ 需手动开
答案
import os, sys, subprocess, re, shutil
def _query_device_status() -> bool:
"""向终端发 DA1 请求,解析 Sixel bit"""
if not sys.stdout.isatty():
return False
try:
# 保存并恢复 stty,防止乱屏
old = subprocess.check_output(['stty', '-g'], stderr=subprocess.DEVNULL)
proc = subprocess.Popen(['sh'], stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
text=True)
out, _ = proc.communicate(
"stty -echo; printf '\\033[c'; read -r -t 0.2 -d c reply; "
"printf '%s' \"$reply\"; stty '" + old.decode() + "'\n", timeout=0.5)
# DA1 响应形如 \033[?62;4c,其中 4 代表 Sixel
return '4' in re.search(r'\033\[\\?([0-9;]+)c', out).group(1).split(';')
except Exception:
return False
def _mini_sixel_test() -> bool:
"""写 1×1 透明 Sixel,看光标是否回显正常"""
if not sys.stdout.isatty():
return False
try:
# 1×1 透明像素,调色板 0 全透明
probe = '\033Pq#0;2;0;0;0#1~~\033\\'
print(probe, end='', flush=True)
# 若终端不支持,通常会原样打印乱码,后续读回提示符即可
return True # 简化版:实际需读回提示符验证无乱码
except Exception:
return False
def terminal_supports_sixel() -> bool:
"""供 Matplotlib 后端调用的公开 API"""
# 1. 白名单快速路径,减少延迟
term = os.environ.get('TERM', '')
if 'sixel' in term or os.environ.get('WEZTERM_EXECUTABLE'):
return True
# 2. 黑名单直接返回
if shutil.which('img2sixel') is None and term.startswith('screen'):
return False
# 3. 运行时探测
return _query_device_status() or _mini_sixel_test()
# Matplotlib 后端内部使用示例
from matplotlib.backends.backend_base import FigureCanvasBase
class FigureCanvasSixel(FigureCanvasBase):
def print_figure(self, filename, dpi=120, **kwargs):
if not terminal_supports_sixel():
# 回退到 base64 内联 png
self._print_png_to_terminal(filename, dpi)
return
# 真正输出 Sixel
self._print_sixel(filename, dpi)
关键点:
- 必须运行时探测,任何静态白名单在国内多变终端场景都会失效;
- 探测失败要有回退,否则在 deepin-terminal、CloudShell 等环境会打印乱码,导致用户投诉;
- Matplotlib 后端只需在
print_figure里调用一次探测,缓存结果,避免每次绘图都阻塞 200 ms。
拓展思考
- GPU 加速与 Sixel 冲突:WezTerm 开启 OpenGL 前端时,Sixel 位图会走独立纹理通道,若 Matplotlib 用
matplotlib.rcParams['webagg.port']同时起 WebAgg,可能导致显存双重占用,需在后端初始化时检测GL_RENDERER并降频刷新。 - Jupyter 内核复用:国内很多高校 JupyterHub 用
tmux持久化会话,前端是 JupyterLab 的xterm.js,此时stdout.isatty()为真,但xterm.js的 Sixel 开关由服务器c.NotebookApp.term_settings控制,需改探测逻辑为:先查JUPYTER_TERMINAL_SETTINGS环境变量,再发 WebSocket 询问xterm-addon-sixel版本。 - 国产终端合规:统信、麒麟系统自带终端基于 Qt,源码闭源,无法通过 DA1 返回位判断,只能调用其私有 D-Bus 接口
com.uniontech.terminal.sixelEnabled(),需写 C++ 扩展并在setup.py里加qdbus条件编译,符合国内信创要求。 - CI 无头测试:GitHub Actions、阿里云 Flow 默认
tty为伪终端,探测必失败,需在pytest里加mock.patch('matplotlib.backends._sixel.terminal_supports_sixel', return_value=True),否则 2000+ 单元测试会跳过 Sixel 分支,降低覆盖率。