蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

读取真实 CLI 快捷键提示并退出

PYTHONWindows ConPTY、Claude Code 2.1.325、Python 3.12 和 pywinpty。terminal_lab.py
terminal_lab.py87 行
import argparse
import json
import os
from pathlib import Path
import re
import socket
import time
from tempfile import TemporaryDirectory

from winpty import PtyProcess

CSI = re.compile(r"\x1b\[[0-?]*[ -/]*[@-~]")


def exercise(exe):
    env = {key: os.environ[key] for key in (
        "SYSTEMROOT", "WINDIR", "PATH", "TEMP", "TMP", "COMSPEC", "LOCALAPPDATA",
        "APPDATA", "ProgramFiles", "USERPROFILE") if key in os.environ}
    with TemporaryDirectory(prefix="mbsky-terminal-lesson-") as directory:
        root = Path(directory)
        profile = workspace = root
        config = json.dumps({"hasCompletedOnboarding": True, "lastOnboardingVersion": "2.1.325"})
        (profile / ".claude.json").write_text(config, encoding="utf-8")
        (profile / "config.json").write_text(config, encoding="utf-8")
        env.update(CLAUDE_CONFIG_DIR=str(profile), CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC="1",
                   DISABLE_AUTOUPDATER="1", DISABLE_TELEMETRY="1", DISABLE_ERROR_REPORTING="1",
                   FORCE_COLOR="0", TERM="xterm-256color", CLAUDE_CODE_SIMPLE="1",
                   ANTHROPIC_BASE_URL="http://127.0.0.1:1", ANTHROPIC_AUTH_TOKEN="fixture-not-real",
                   ANTHROPIC_MODEL="sample-pro", API_TIMEOUT_MS="3000", HTTP_PROXY="http://127.0.0.1:1",
                   HTTPS_PROXY="http://127.0.0.1:1")
        argv = [str(exe), "--permission-mode", "plan", "--strict-mcp-config", "--setting-sources", ""]
        session = PtyProcess.spawn(argv, cwd=str(workspace), env=env, dimensions=(40,120), backend="0")
        session.fileobj.settimeout(.18)
        events = []

        def wait_for(label, marker):
            end = time.monotonic() + 12
            transcript = ""
            while time.monotonic() < end:
                try:
                    transcript += session.read(4096)
                except (socket.timeout, EOFError):
                    if not session.pty.isalive():
                        break
                normalized = re.sub(r"\s+"," ",CSI.sub(" ",transcript)).lower()
                if marker in normalized:
                    events.append({"event":label,"observed":marker})
                    return normalized
            raise TimeoutError(f"{label}: {CSI.sub(' ', transcript)[-450:]}")

        try:
            wait_for("trust_prompt","to cancel")
            time.sleep(1.1)
            session.write("\x1b[B")
            wait_for("trust_selection","❯")
            time.sleep(1.1)
            session.write("\r")
            wait_for("plan_footer","plan mode on")
            time.sleep(.5)
            session.write("?")
            panel = wait_for("help_panel","for shell mode")
            if "for commands" in panel:
                events.append({"event":"command_hint","observed":"for commands"})
            session.write("\x1b")
            wait_for("back_to_prompt","plan mode on")
            session.write("\x03")
            wait_for("quit_confirmation","press ctrl-c again to exit")
            session.write("\x03")
            end = time.monotonic() + 6
            while session.pty.isalive() and time.monotonic() < end:
                try:
                    session.read(4096)
                except (socket.timeout, EOFError):
                    pass
            assert not session.pty.isalive()
            events.append({"event":"exit","observed":session.exitstatus})
        finally:
            session.close(force=True)
    return events


if __name__ == "__main__":
    parser=argparse.ArgumentParser()
    parser.add_argument("claude",type=Path)
    params=parser.parse_args()
    print(json.dumps(exercise(params.claude.resolve(strict=True))))
本例需在 Windows ConPTY、Claude Code 2.1.325、Python 3.12 和 pywinpty。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows ConPTY、Claude Code 2.1.325、Python 3.12 和 pywinpty。

入口文件:projects/claude-code-terminal/terminal_lab.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 terminal_lab.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows ConPTY、Claude Code 2.1.325、Python 3.12 和 pywinpty。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Claude Code

课程关联工程包(登记关联42章) · 含当前章节或实例 · mbskycom202612a3117.zip

下载课程关联工程包:Claude Code

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3146.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习