headless-terminal

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Headless Terminal Implementation

无头终端实现

Overview

概述

This skill guides the implementation of headless terminal interfaces—programmatic wrappers that control shell sessions without a visible terminal UI. These implementations typically involve spawning shell processes, sending input (keystrokes, commands), and capturing output.
本技能指导你实现无头终端接口——即无需可视化终端UI、可程序化控制Shell会话的包装器。这类实现通常涉及启动Shell进程、发送输入(按键、命令)以及捕获输出。

Approach

实现方法

Step 1: Understand the Interface Contract

步骤1:理解接口约定

Before implementing, thoroughly read and understand the interface to be implemented:
  1. Identify all required methods and their signatures
  2. Note return types and expected behaviors
  3. Check for optional methods or features
  4. Look for existing implementations or tests that clarify expected behavior
在开始实现前,需全面阅读并理解要实现的接口:
  1. 识别所有必需的方法及其签名
  2. 注意返回类型和预期行为
  3. 检查是否存在可选方法或功能
  4. 参考现有实现或测试案例,明确预期行为

Step 2: Select the Underlying Library

步骤2:选择底层库

Common libraries for terminal emulation in Python:
LibraryBest ForTrade-offs
pexpect
Interactive terminal emulation, pattern matchingHigher-level API, good for expect/send patterns
pty
Low-level pseudo-terminal controlMore control, but more boilerplate
subprocess
Simple non-interactive commandsLimited for true terminal emulation
Decision criteria to document:
  • Does the task require interactive input (passwords, prompts)? →
    pexpect
  • Does the task need low-level terminal control? →
    pty
  • Is it purely non-interactive command execution? →
    subprocess
    may suffice
Document the choice explicitly with reasoning for future maintainability.
Python中用于终端仿真的常用库:
适用场景权衡点
pexpect
交互式终端仿真、模式匹配高层级API,适用于expect/send模式
pty
底层伪终端控制控制粒度更细,但需要更多样板代码
subprocess
简单的非交互式命令执行对于真正的终端仿真能力有限
需记录的决策标准:
  • 任务是否需要交互式输入(如密码、提示符)?→ 选择
    pexpect
  • 任务是否需要底层终端控制?→ 选择
    pty
  • 是否仅需执行非交互式命令?→
    subprocess
    可能足够
明确记录选择结果及理由,以便未来维护。

Step 3: Handle Shell Configuration

步骤3:处理Shell配置

When spawning a shell process, consider these configuration options:
Interactive mode (
-i
flag):
  • Ensures startup files (
    .bashrc
    ,
    .bash_profile
    ) are sourced
  • Affects signal handling behavior
  • Required if tests verify startup file sourcing
Echo behavior:
  • echo=False
    in pexpect prevents input from appearing in output
  • Consider whether the use case needs to see echoed input
Terminal dimensions:
  • Default
    (24, 80)
    is standard terminal size
  • May affect output formatting for commands that detect terminal width
  • Document why specific dimensions are chosen
启动Shell进程时,需考虑以下配置选项:
交互模式(
-i
参数):
  • 确保启动文件(
    .bashrc
    .bash_profile
    )被加载
  • 影响信号处理行为
  • 如果测试需要验证启动文件加载,则必须启用
回显行为:
  • pexpect中的
    echo=False
    可防止输入内容出现在输出中
  • 需根据使用场景判断是否需要显示回显的输入内容
终端尺寸:
  • 默认
    (24, 80)
    是标准终端尺寸
  • 可能影响那些会检测终端宽度的命令的输出格式
  • 记录选择特定尺寸的理由

Step 4: Implement Core Functionality

步骤4:实现核心功能

Focus on implementing exactly what the interface requires:
  1. Process lifecycle management - Spawn, check liveness, terminate
  2. Input handling - Send keystrokes, handle special keys (Ctrl+C, etc.)
  3. Output capture - Read available output, handle buffering
  4. Resource cleanup - Proper termination, context manager support
专注于实现接口要求的核心功能:
  1. 进程生命周期管理 - 启动、检查存活状态、终止
  2. 输入处理 - 发送按键指令,处理特殊按键(如Ctrl+C等)
  3. 输出捕获 - 读取可用输出,处理缓冲问题
  4. 资源清理 - 正确终止进程,支持上下文管理器

Step 5: Address Edge Cases

步骤5:处理边缘情况

Explicitly handle these scenarios:
Edge CaseHandling Strategy
Shell exits unexpectedlyCheck process liveness before operations
Long-running commandsConfigurable timeouts, background execution support
Non-ASCII charactersExplicit encoding handling (UTF-8 typically)
Race conditionsAppropriate delays between send and read operations
Command cancellationProper signal handling (SIGINT for Ctrl+C)
需显式处理以下场景:
边缘情况处理策略
Shell意外退出在操作前检查进程是否存活
长时间运行的命令支持可配置超时、后台执行
非ASCII字符显式处理编码(通常为UTF-8)
竞争条件在发送和读取操作之间设置适当延迟
命令取消正确处理信号(如使用SIGINT实现Ctrl+C)

Verification Strategies

验证策略

Testing Approach

测试方法

Create focused tests for each capability:
  1. Basic functionality - Import, instantiation
  2. Non-interactive commands - Simple command execution and output
  3. Interactive commands - Commands requiring input
  4. Signal handling - Ctrl+C cancellation
  5. Shell state - Variable persistence, environment
  6. Startup configuration - Verify startup files are sourced
  7. Background execution - Long-running command handling
为每项功能创建针对性测试:
  1. 基础功能 - 导入、实例化
  2. 非交互式命令 - 简单命令执行与输出验证
  3. 交互式命令 - 需要输入的命令测试
  4. 信号处理 - Ctrl+C取消命令测试
  5. Shell状态 - 变量持久化、环境变量测试
  6. 启动配置 - 验证启动文件是否被加载
  7. 后台执行 - 长时间运行命令的处理测试

Verification Guidelines

验证指南

  • Run the test suite to verify all functionality
  • Avoid redundant manual verification after tests pass
  • If a single comprehensive test file exists, use it rather than creating separate verification scripts
  • 运行测试套件以验证所有功能
  • 测试通过后避免冗余的手动验证
  • 如果已有一个全面的测试文件,直接使用它,无需创建单独的验证脚本

Common Pitfalls

常见陷阱

Scope Management

范围管理

  • Implement only what is required - Avoid adding unrequested features like extra utility methods
  • If additional methods seem useful, note them but don't implement unless asked
  • Context manager support is often expected but verify it's in the interface
  • 仅实现所需功能 - 避免添加未要求的功能,如额外的工具方法
  • 如果觉得某些额外方法有用,可记录下来,但除非被要求否则不要实现
  • 上下文管理器支持通常是预期功能,但需先确认它是否在接口要求范围内

Efficiency

效率

  • Avoid redundant searches - If searching for a class, one targeted search is sufficient
  • Don't duplicate verification - If tests pass, additional manual checks are unnecessary
  • Don't create example files unless explicitly requested
  • 避免重复搜索 - 如果要查找某个类,一次针对性搜索即可
  • 不要重复验证 - 测试通过后,无需额外手动检查
  • 除非明确要求,否则不要创建示例文件

Documentation Gaps

文档缺失

Common decisions that should be documented but often aren't:
  1. Why the chosen library over alternatives
  2. Why specific shell flags are used
  3. Why specific default values were selected
  4. Thread safety considerations (or explicit statement that it's not thread-safe)
以下决策通常需要记录但常被忽略:
  1. 选择当前库而非其他替代库的理由
  2. 使用特定Shell参数的原因
  3. 选择特定默认值的依据
  4. 线程安全性考量(或明确声明不支持线程安全)

Error Handling

错误处理

Consider and document handling for:
  • Invalid keystroke sequences
  • Terminal process termination
  • Timeout scenarios
  • Permission issues
需考虑并记录以下场景的处理方式:
  • 无效的按键序列
  • 终端进程终止
  • 超时场景
  • 权限问题

Implementation Checklist

实现检查清单

Before considering the implementation complete:
  • All interface methods are implemented
  • Library choice is documented with reasoning
  • Configuration decisions are justified
  • Edge cases are explicitly handled or documented as out of scope
  • Tests cover all required functionality
  • No unrequested features were added
  • Resource cleanup is properly implemented
在确认实现完成前,需完成以下检查:
  • 所有接口方法均已实现
  • 已记录库的选择及理由
  • 已证明配置决策的合理性
  • 边缘情况已被显式处理或记录为超出范围
  • 测试覆盖了所有必需功能
  • 未添加任何未要求的功能
  • 已正确实现资源清理