Pty API Reference
April 16, 2026 ยท View on GitHub
๐ก Async Version: This documentation covers the synchronous API. For async/await support, see
AsyncPtywhich provides the same functionality with async methods.
๐ป Related Tutorial
- PTY Terminal Guide - Learn how to use interactive terminal sessions in cloud environments
Overview
The PTY module provides interactive terminal sessions in cloud sandbox environments. Unlike the Command module which executes single commands, PTY gives you a persistent, interactive shell with real-time streaming output, terminal resize support, and session lifecycle management.
logger
logger = logging.getLogger(__name__)
PTY_TARGET
PTY_TARGET = "PTY_SERVER"
DEFAULT_ENVS
DEFAULT_ENVS = {
"TERM": "xterm-256color",
"LANG": "en_US.UTF-8",
}
MAX_TERMINAL_SIZE
MAX_TERMINAL_SIZE = 500
PtySession
@dataclass
class PtySession()
Read-only snapshot of a PTY session.
pty_session_id: str
pty_session_id = None
cols: int
cols = None
rows: int
rows = None
status: str
status = None
exit_code: Optional[int]
exit_code = None
PtyHandle
class PtyHandle()
Active connection to a PTY session.
init
def __init__(self, pty_session_id: str,
pty_module: "Pty",
on_data: Optional[Callable[[bytes], None]] = None)
pty_session_id
@property
def pty_session_id() -> str
is_connected
@property
def is_connected() -> bool
exit_code
@property
def exit_code() -> Optional[int]
send_input
def send_input(data: bytes) -> None
Send input bytes to the PTY.
resize
def resize(cols: int, rows: int) -> None
Resize the terminal.
kill
def kill() -> None
Kill the PTY process (SIGKILL).
wait
def wait(timeout_s: Optional[float] = None) -> int
Wait for the PTY process to exit. Returns the exit code.
disconnect
def disconnect() -> None
Disconnect from the PTY (local only, process continues on server).
Pty
class Pty()
PTY module entry point, accessed as session.pty.
init
def __init__(self, session)
create
def create(cols: int = 80,
rows: int = 24,
cwd: Optional[str] = None,
envs: Optional[Dict[str, str]] = None,
shell: Optional[str] = None,
on_data: Optional[Callable[[bytes], None]] = None,
timeout_s: Optional[float] = None) -> PtyHandle
Create a new PTY session and return a PtyHandle.
list
def list() -> List[PtySession]
List all active PTY sessions.
connect
def connect(pty_session_id: str,
on_data: Optional[Callable[[bytes], None]] = None) -> PtyHandle
Connect to an existing PTY session.
kill
def kill(pty_session_id: str) -> None
Kill a PTY session by ID.
Best Practices
- Always disconnect or wait when done with a PTY handle
- Use carriage return (\r) to submit commands instead of newline
- Handle the on_data callback efficiently as it may be called frequently
- Set terminal size to match the client for correct line wrapping
- Use appropriate timeouts with wait() to avoid blocking indefinitely
See Also
Related APIs:
Documentation generated automatically from source code using pydoc-markdown.