> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mirage.strukto.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Machines in Python

> Declare machines in Python, change them on a live workspace, and start programs from code.

A machine is where programs such as `python3` and `node` run: inside Mirage
(`in_process` with a runtime), on the host, or in a container or sandbox.
[Machines](https://docs.mirage.strukto.ai/home/setup/machine/overview.md) explains routing, captures and each
provider. This page covers what is particular to the Python SDK; each
machine's page has its install and an example.

## Declare machines

Each entry in `Workspace(machines={...})` is a config dict, a runtime object
or a machine handle. By default, the first machine whose `captures` names a program runs
it:

```python theme={null}
from mirage import MountMode, RAMVFS, Workspace

ws = Workspace(
    {"/data": RAMVFS()},
    mode=MountMode.EXEC,
    machines={
        "py": {"provider": "in_process", "runtime": "monty"},
        "box": {"provider": "docker", "container": "my-sandbox"},
    },
)
await ws.shell("python3 -c 'print(1 + 1)'")
```

## Change them on a live workspace

Machine providers such as docker and ssh can only be set in the
constructor. On a running workspace, `add_machine(name, spec)` adds a runtime
or a `host` or `remote` machine, `remove_machine(name)` removes one, and `engines()` lists
them:

```python theme={null}
from mirage.runtime.python import WasiRuntime

await ws.remove_machine("py")
ws.add_machine("py", WasiRuntime(config={"home": "/opt/cpython-wasi"}))
```

`python3` moves to the new machine at once. A running line finishes before
its removed runtime closes, a removed instance cannot be added again, and
`workspace` cannot be removed. `register_runtime(name, cls)` makes your own
runtime class available by name in YAML.

## Child processes

`ws.spawn` starts a program from your code with the same policy checks as a
shell command.

```python theme={null}
from mirage.execution.process.types import SpawnRequest

child = ws.spawn(SpawnRequest(("cat",)))
result = await child.communicate(b"hello\n")
```

## Python SDK notes

* **Local:** with neither `home` nor `MIRAGE_LOCAL_HOME`, `python3` is the
  interpreter running Mirage.
* **Machines:** `mount_type: ssh` needs `pip install 'mirage-ai[ssh]'` on
  the host. The `ssh` machine matches `host` against `~/.ssh/config`.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.