dockerpty: Pseudo-TTY handler for Docker Python client

0.4.1 · maintenance · verified Sun Apr 12

dockerpty is a Python library that provides functionality to operate the pseudo-tty (PTY) allocated to a Docker container, using the Python client. It enables bridging the input and output streams of a Docker container's terminal with the host's terminal, allowing for interactive shell sessions within containers. The library's last release was in February 2016.

Warnings

Install

Imports

Quickstart

This example demonstrates how to create and attach to an interactive shell within a Docker container using `dockerpty`. It uses the `docker.Client()` class from the older `docker-py` library to interact with the Docker daemon. The container is created with `stdin_open=True` and `tty=True` to enable interactive terminal functionality. The `dockerpty.start()` function then takes control of the current terminal, piping its input/output to/from the container's PTY.

import docker
import dockerpty
import os

# Ensure docker-py is installed: pip install docker-py
# This example uses the older docker-py client API.
# For modern Docker SDK for Python, direct use of `attach()` or `exec_run()` might be preferred.

# For demonstration, ensure a Docker daemon is running.
# For this example to be interactive, run it in a terminal.

try:
    # Using the older docker.Client() from docker-py
    # Modern Docker SDK uses docker.from_env() or docker.DockerClient()
    # For this example to work with docker-py, install it:
    # pip install docker-py
    client = docker.Client(base_url=os.environ.get('DOCKER_HOST', 'unix://var/run/docker.sock'))

    # Create a container with TTY and stdin_open for interactive use
    container = client.create_container(
        image='busybox:latest',
        stdin_open=True,
        tty=True,
        command='/bin/sh',
    )
    print(f"Container created with ID: {container['Id']}")

    # Start the container
    client.start(container)

    print("Attaching to container's PTY. Type 'exit' to quit the shell and container.")
    # Attach to the container's pseudo-terminal
    # Passing logs=1 is recommended due to an internal DeprecationWarning in dockerpty 0.4.1
    dockerpty.start(client, container, logs=1)

    print(f"Container {container['Id']} exited.")

except Exception as e:
    print(f"An error occurred: {e}")
    print("Please ensure Docker daemon is running and `docker-py` is installed (not just `docker` SDK). ")
    print("This library is designed for an older Docker client version.")
finally:
    # Clean up the container
    if 'container' in locals() and client:
        try:
            client.remove_container(container, v=True, force=True)
            print(f"Container {container['Id']} removed.")
        except Exception as e:
            print(f"Error removing container: {e}")

view raw JSON →