Python library to use the pseudo-tty of a docker container
—
The core classes that handle pseudo-terminal allocation, management, and control. These classes provide the foundational layer for all dockerpty operations, managing the complexities of terminal hijacking, signal handling, and resource cleanup.
The main class that wraps the pseudo-TTY (PTY) allocated to a docker container and manages it via the current process' TTY.
class PseudoTerminal:
def __init__(self, client, operation):
"""
Initialize the PTY using the docker.Client instance and operation.
Parameters:
- client: Docker client instance
- operation: RunOperation or ExecOperation instance
"""
def start(self, sockets=None):
"""
Start PTY management with terminal hijacking.
This method takes over the current process' TTY until the container's PTY
is closed. Handles stream pumping, signal handlers, and resource cleanup.
Parameters:
- sockets: tuple of (stdin_socket, stdout_socket, stderr_socket), optional
Returns:
None - blocks until PTY is closed
"""
def resize(self, size=None):
"""
Resize the container's PTY.
Parameters:
- size: tuple of (height, width), optional. If None, determined by current TTY size
Returns:
None
"""
def sockets(self):
"""
Return the operation sockets.
Returns:
Sockets from the underlying operation
"""Usage example:
import docker
from dockerpty import PseudoTerminal, RunOperation
client = docker.Client()
container = client.create_container(
image='busybox:latest',
stdin_open=True,
tty=True,
command='/bin/sh',
)
# Create operation and start PTY
operation = RunOperation(client, container)
pty = PseudoTerminal(client, operation)
pty.start() # This hijacks the terminalHandles SIGWINCH signals to keep the PTY correctly sized when the terminal window is resized.
class WINCHHandler:
def __init__(self, pty):
"""
Initialize a new WINCH handler for the given PTY.
Initializing a handler has no immediate side-effects. The start()
method must be invoked for signals to be trapped.
Parameters:
- pty: PseudoTerminal instance to handle resize signals for
"""
def __enter__(self):
"""
Context manager entry - starts signal handling.
Returns:
self
"""
def __exit__(self, *_):
"""
Context manager exit - stops signal handling.
Parameters:
- *_: Exception information (ignored)
Returns:
None
"""
def start(self):
"""
Start trapping WINCH signals and resizing the PTY.
This method saves the previous WINCH handler so it can be restored on stop().
Returns:
None
"""
def stop(self):
"""
Stop trapping WINCH signals and restore the previous WINCH handler.
Returns:
None
"""Usage example:
from dockerpty import WINCHHandler, PseudoTerminal
# Usually used as context manager
with WINCHHandler(pty):
# PTY will be automatically resized when terminal window changes
pty.start()The PseudoTerminal class ensures proper cleanup of:
Install with Tessl CLI
npx tessl i tessl/pypi-dockerpty