or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

build.mdclient.mdcompose.mdconfig.mdcontainers.mdcontext.mdimages.mdindex.mdmanifest.mdnetworks.mdnode.mdplugin.mdpod.mdsecret.mdservice.mdstack.mdswarm.mdsystem.mdtask.mdtrust.mdvolumes.md
tile.json

tessl/pypi-python-on-whales

A Docker client for Python, designed to be fun and intuitive!

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/python-on-whales@0.78.x

To install, run

npx @tessl/cli install tessl/pypi-python-on-whales@0.78.0

index.mddocs/

Python-on-Whales

A comprehensive Python client library for Docker that makes container management intuitive and fun. Python-on-whales provides a Pythonic interface that mirrors Docker CLI commands, enabling developers to perform all Docker operations programmatically including running containers, building images, managing volumes, and orchestrating multi-container applications with Docker Compose.

Package Information

  • Package Name: python-on-whales
  • Language: Python
  • Installation: pip install python-on-whales

Core Imports

import python_on_whales

Standard usage patterns:

from python_on_whales import docker

For specific components:

from python_on_whales import (
    DockerClient, Container, Image, Volume, Network, Builder,
    Config, Context, DockerContextConfig, KubernetesContextConfig,
    Node, Plugin, Pod, Secret, Service, Stack, Task, ManifestList,
    ContainerStats, SystemInfo, Version, DockerException, ClientNotFoundError
)

Basic Usage

from python_on_whales import docker

# Run a simple container
result = docker.run("hello-world")
print(result)

# Run container with options
output = docker.run(
    "ubuntu:20.04", 
    ["echo", "Hello from container"], 
    remove=True
)
print(output)

# List running containers
containers = docker.ps()
for container in containers:
    print(f"Container: {container.name} - Status: {container.state}")

# Pull and manage images
docker.pull("python:3.9")
images = docker.images()
for image in images:
    print(f"Image: {image.repo_tags}")

# Work with volumes
volume = docker.volume.create("my-volume")
volumes = docker.volume.list()

Architecture

Python-on-whales is built around a modular architecture that provides both high-level convenience and low-level control:

  • DockerClient: Main interface providing access to all Docker functionality through component CLIs
  • Component CLIs: Specialized interfaces for different Docker objects (containers, images, networks, etc.)
  • Object Models: Pydantic-based models representing Docker objects with methods for operations and state management
  • Exception Handling: Comprehensive error handling with specific exceptions for different failure scenarios
  • Backend Support: Works with Docker, Podman, and other Docker-compatible clients

The library supports both synchronous operations and streaming for long-running commands, with extensive configuration options for different deployment scenarios.

Capabilities

Client Configuration

Main Docker client interface and configuration options for connecting to different Docker daemons, setting up contexts, and managing authentication.

class DockerClient:
    def __init__(
        self,
        config: Optional[str] = None,
        context: Optional[str] = None,
        debug: bool = False,
        host: Optional[str] = None,
        log_level: str = "info",
        tls: bool = False,
        tlscacert: Optional[str] = None,
        compose_files: Optional[List[str]] = None,
        compose_profiles: Optional[List[str]] = None,
        compose_env_file: Optional[str] = None,
        compose_project_name: Optional[str] = None,
        compose_project_directory: Optional[str] = None,
        compose_compatibility: bool = False,
        client_call: Optional[List[str]] = None,
        client_type: str = "docker"
    ): ...
    
    def version(self) -> Version: ...
    def login(self, server: Optional[str] = None, username: Optional[str] = None, password: Optional[str] = None): ...
    def logout(self, server: Optional[str] = None): ...

Client Configuration

Container Operations

Comprehensive container lifecycle management including creation, execution, monitoring, and cleanup operations.

def run(
    image: str,
    command: Optional[List[str]] = None,
    remove: bool = False,
    detach: bool = False,
    envs: Optional[Dict[str, str]] = None,
    volumes: Optional[List[str]] = None,
    ports: Optional[Dict[str, str]] = None,
    **kwargs
) -> Union[str, Container]: ...

def create(image: str, command: Optional[List[str]] = None, **kwargs) -> Container: ...
def ps(all: bool = False, filters: Optional[Dict[str, str]] = None) -> List[Container]: ...
def logs(container: str, follow: bool = False, tail: Optional[int] = None) -> str: ...

Container Operations

Image Management

Image building, pulling, pushing, and management operations including legacy build and modern buildx support.

def pull(image_name: str, platform: Optional[str] = None) -> Image: ...
def push(image_name: str) -> str: ...
def build(context_path: str, tags: Optional[List[str]] = None, **kwargs) -> Image: ...
def images(all: bool = False) -> List[Image]: ...
def remove(images: Union[str, List[str]], force: bool = False) -> None: ...

Image Management

Network Management

Docker network creation, management, and container connectivity operations.

def create(name: str, driver: Optional[str] = None, **kwargs) -> Network: ...
def connect(network: str, container: str, **kwargs) -> None: ...
def disconnect(network: str, container: str, force: bool = False) -> None: ...
def list(filters: Optional[Dict[str, str]] = None) -> List[Network]: ...

Network Management

Volume Management

Docker volume creation, management, and data persistence operations.

def create(name: Optional[str] = None, driver: Optional[str] = None, **kwargs) -> Volume: ...
def list(filters: Optional[Dict[str, str]] = None) -> List[Volume]: ...
def remove(volumes: Union[str, List[str]], force: bool = False) -> None: ...

Volume Management

Docker Compose Integration

Complete Docker Compose support for multi-container application orchestration.

def up(services: Optional[List[str]] = None, detach: bool = False, build: bool = False, **kwargs) -> None: ...
def down(remove_orphans: bool = False, volumes: bool = False, **kwargs) -> None: ...
def build(services: Optional[List[str]] = None, **kwargs) -> None: ...
def ps(services: Optional[List[str]] = None) -> List[Container]: ...

Docker Compose

Build Operations

Advanced build operations using Docker Buildx for multi-platform builds and BuildKit features.

def build(
    context_path: str,
    tags: Optional[List[str]] = None,
    platforms: Optional[List[str]] = None,
    push: bool = False,
    **kwargs
) -> Image: ...

def create(name: str, driver: Optional[str] = None, **kwargs) -> Builder: ...

Build Operations

System Operations

System-level Docker operations including information retrieval, cleanup, and monitoring.

def info() -> SystemInfo: ...
def df() -> DiskFreeResult: ...
def prune(all: bool = False, volumes: bool = False) -> None: ...
def events(filters: Optional[Dict[str, str]] = None) -> Iterator[dict]: ...

System Operations

Swarm Management

Docker Swarm operations for container orchestration including nodes, services, secrets, and configs.

def init(advertise_addr: Optional[str] = None, **kwargs) -> str: ...
def join(token: str, manager_addr: str, **kwargs) -> None: ...
def leave(force: bool = False) -> None: ...

Swarm Management

Config Management

Docker swarm configuration management for securely storing non-sensitive configuration data like application settings and template files.

def create(
    name: str,
    file: Optional[str] = None,
    labels: Optional[Dict[str, str]] = None,
    template_driver: Optional[str] = None
) -> Config: ...

def inspect(x: Union[str, List[str]]) -> Union[Config, List[Config]]: ...
def list(filters: Optional[Dict[str, str]] = None) -> List[Config]: ...
def remove(x: Union[str, List[str]]) -> None: ...

Config Management

Context Management

Docker context management for switching between different Docker environments (local, remote, Kubernetes).

def create(
    context_name: str,
    *,
    description: Optional[str] = None,
    docker: Optional[DockerContextConfig] = None,
    kubernetes: Optional[KubernetesContextConfig] = None
) -> Context: ...

def inspect(x: Optional[str] = None) -> Context: ...
def list() -> List[Context]: ...
def use(context: Union[str, Context]) -> None: ...
def remove(x: Union[str, List[str]], force: bool = False) -> None: ...

Context Management

Node Management

Docker swarm node management for controlling worker and manager nodes in a swarm cluster.

def inspect(x: Union[str, List[str]]) -> Union[Node, List[Node]]: ...
def list() -> List[Node]: ...
def promote(x: Union[str, List[str]]) -> None: ...
def demote(x: Union[str, List[str]]) -> None: ...
def update(node: Union[str, Node], availability: Optional[str] = None, **kwargs) -> None: ...
def ps(x: Optional[Union[str, List[str]]] = None) -> List[Task]: ...
def remove(x: Union[str, List[str]], force: bool = False) -> None: ...

Node Management

Plugin Management

Docker plugin management for extending Docker functionality with third-party plugins.

def install(plugin_name: str, **kwargs) -> Plugin: ...
def create(plugin_name: str, plugin_data_directory: str, compress: bool = False) -> Plugin: ...
def enable(plugin: Union[str, Plugin], timeout: Optional[int] = None) -> None: ...
def disable(plugin: Union[str, Plugin], force: bool = False) -> None: ...
def inspect(x: Union[str, List[str]]) -> Union[Plugin, List[Plugin]]: ...
def list() -> List[Plugin]: ...
def remove(x: Union[str, List[str]], force: bool = False) -> None: ...

Plugin Management

Pod Management

Note: Podman-specific functionality

Podman pod management for grouping containers with shared namespaces, networking, and storage.

def create(name: Optional[str] = None, **kwargs) -> Pod: ...
def start(x: Union[str, List[str]]) -> None: ...
def stop(x: Union[str, List[str]], time: Optional[int] = None) -> None: ...
def restart(x: Union[str, List[str]]) -> None: ...
def pause(x: Union[str, List[str]]) -> None: ...
def unpause(x: Union[str, List[str]]) -> None: ...
def kill(x: Union[str, List[str]], signal: Optional[str] = None) -> None: ...
def inspect(x: Union[str, List[str]]) -> Union[Pod, List[Pod]]: ...
def list(filters: Sequence[str] = ()) -> List[Pod]: ...
def remove(x: Union[str, List[str]], force: bool = False, **kwargs) -> None: ...

Pod Management

Secret Management

Docker swarm secret management for securely storing sensitive data like passwords, certificates, and API keys.

def create(
    name: str,
    file: Optional[str] = None,
    driver: Optional[str] = None,
    labels: Optional[Dict[str, str]] = None
) -> Secret: ...

def inspect(x: Union[str, List[str]]) -> Union[Secret, List[Secret]]: ...
def list(filters: Sequence[str] = ()) -> List[Secret]: ...
def remove(x: Union[str, List[str]]) -> None: ...

Secret Management

Service Management

Docker swarm service management for running and orchestrating containerized applications across multiple nodes.

def create(image: str, command: Optional[List[str]] = None, **kwargs) -> Service: ...
def inspect(x: Union[str, List[str]]) -> Union[Service, List[Service]]: ...
def list(filters: Sequence[str] = ()) -> List[Service]: ...
def logs(service: Union[str, Service], **kwargs) -> Union[str, Iterable[Tuple[str, bytes]]]: ...
def ps(x: Union[str, List[str]]) -> List[Task]: ...
def update(service: Union[str, Service], **kwargs) -> None: ...
def scale(new_scales: Dict[str, int], detach: bool = False) -> None: ...
def remove(services: Union[str, List[str]]) -> None: ...

Service Management

Stack Management

Docker stack management for deploying multi-service applications using Docker Compose files in swarm mode.

def deploy(name: str, compose_files: List[str], **kwargs) -> None: ...
def list() -> List[Stack]: ...
def services(stack: Union[str, Stack]) -> List[Service]: ...
def ps(x: Union[str, Stack]) -> List[Task]: ...
def remove(x: Union[str, List[str]]) -> None: ...

Stack Management

Task Management

Docker swarm task inspection and monitoring for individual running instances of services on specific nodes.

def list() -> List[Task]: ...
def inspect(x: Union[str, List[str]]) -> Union[Task, List[Task]]: ...

Task Management

Manifest Management

Docker manifest list management for multi-architecture image support.

def create(name: str, manifests: List[str], **kwargs) -> ManifestList: ...
def annotate(name: str, manifest: str, **kwargs) -> None: ...
def inspect(x: Union[str, ManifestList]) -> ManifestList: ...
def push(x: Union[str, ManifestList], **kwargs) -> None: ...
def remove(manifest_lists: Union[str, List[str]]) -> None: ...

Manifest Management

Trust Management

Note: Currently not implemented

Docker Content Trust for image signing and verification (placeholder for future functionality).

def inspect() -> None: ...  # Not implemented
def revoke() -> None: ...   # Not implemented  
def sign() -> None: ...     # Not implemented

Trust Management

Types

class Container:
    id: str
    name: str
    image: str
    state: str
    status: str
    ports: Dict[str, Any]
    mounts: List[Dict[str, Any]]
    
    def remove(self, force: bool = False, volumes: bool = False) -> None: ...
    def start(self) -> None: ...
    def stop(self, timeout: Optional[int] = None) -> None: ...
    def restart(self, timeout: Optional[int] = None) -> None: ...
    def kill(self, signal: str = "SIGKILL") -> None: ...
    def pause(self) -> None: ...
    def unpause(self) -> None: ...
    def logs(self, follow: bool = False, tail: Optional[int] = None) -> str: ...
    def execute(self, command: List[str], **kwargs) -> str: ...

class Image:
    id: str
    repo_tags: List[str]
    size: int
    created: str
    
    def remove(self, force: bool = False) -> None: ...
    def tag(self, repository: str, tag: Optional[str] = None) -> None: ...
    def save(self, output_path: str) -> None: ...

class Volume:
    name: str
    driver: str
    mountpoint: str
    
    def remove(self, force: bool = False) -> None: ...

class Network:
    id: str
    name: str
    driver: str
    scope: str
    
    def remove(self) -> None: ...

class Builder:
    name: str
    driver: str
    nodes: List[Dict[str, Any]]
    
    def remove(self) -> None: ...

class SystemInfo:
    id: str
    containers: int
    images: int
    server_version: str
    architecture: str
    operating_system: str
    kernel_version: str

class Version:
    client: Optional[Dict[str, Any]]
    server: Optional[Dict[str, Any]]

class DockerException(Exception):
    docker_command: List[str]
    return_code: int
    stdout: Optional[str]
    stderr: Optional[str]

class ClientNotFoundError(Exception):
    pass

class Config:
    id: str
    version: DockerObjectVersion
    created_at: datetime
    updated_at: datetime
    spec: ConfigSpec
    
    def remove(self) -> None: ...

class Context:
    name: str
    metadata: Dict[str, Any]
    endpoints: Dict[str, Any]
    tls_material: Dict[str, Any]
    storage: Dict[str, Any]
    
    def remove(self, force: bool = False) -> None: ...
    def use(self) -> None: ...

class DockerContextConfig:
    def __init__(
        self,
        host: str,
        ca_cert: Optional[str] = None,
        cert: Optional[str] = None,
        key: Optional[str] = None,
        skip_tls_verify: bool = False
    ): ...

class KubernetesContextConfig:
    def __init__(
        self,
        config_file: Optional[str] = None,
        context_override: Optional[str] = None,
        namespace_override: Optional[str] = None
    ): ...

class Node:
    id: str
    version: DockerObjectVersion
    created_at: datetime
    updated_at: datetime
    spec: NodeSpec
    description: NodeDescription
    status: NodeStatus
    manager_status: Optional[ManagerStatus]
    
    def update(self, **kwargs) -> None: ...
    def ps(self) -> List[Task]: ...

class Plugin:
    id: str
    name: str
    enabled: bool
    settings: PluginSettings
    plugin_reference: str
    config: PluginConfig
    
    def disable(self, force: bool = False) -> None: ...
    def enable(self, timeout: Optional[int] = None) -> None: ...
    def remove(self, force: bool = False) -> None: ...

class Pod:
    id: str
    name: str
    created: str
    state: str
    hostname: str
    labels: Dict[str, str]
    containers: List[Dict[str, Any]]
    
    def start(self) -> None: ...
    def stop(self, time: Optional[int] = None) -> None: ...
    def remove(self, force: bool = False, **kwargs) -> None: ...

class Secret:
    id: str
    created_at: datetime
    updated_at: datetime
    spec: SecretSpec
    
    def remove(self) -> None: ...

class Service:
    id: str
    version: DockerObjectVersion
    created_at: datetime
    updated_at: datetime
    spec: ServiceSpec
    endpoint: ServiceEndpoint
    
    def scale(self, new_scale: int, detach: bool = False) -> None: ...
    def update(self, **kwargs) -> None: ...
    def remove(self) -> None: ...
    def ps(self) -> List[Task]: ...

class Stack:
    name: str
    services: int
    orchestrator: str
    
    def remove(self) -> None: ...
    def ps(self) -> List[Task]: ...
    def services(self) -> List[Service]: ...

class Task:
    id: str
    version: DockerObjectVersion
    created_at: datetime
    updated_at: datetime
    name: str
    service_id: str
    node_id: str
    desired_state: str
    status: TaskStatus

class ManifestList:
    name: str
    schema_version: int
    media_type: str
    manifests: List[ManifestDescriptor]
    
    def remove(self) -> None: ...

class ContainerStats:
    container_id: str
    name: str
    cpu_percentage: float
    memory_usage: int
    memory_limit: int
    memory_percentage: float
    network_rx: int
    network_tx: int
    block_read: int
    block_write: int
    pids: int

class DockerObjectVersion:
    index: int

class DiskFreeResult:
    images_size: int
    containers_size: int
    volumes_size: int
    build_cache_size: int