> ## 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.

# Pyodide

> Run Python and packages such as numpy in the TypeScript SDK, in Node and browsers.

[Pyodide](https://pyodide.org) runs Python with packages such as numpy in
Node and browsers. Workspace file access follows the same permissions as
shell commands, and each command starts with fresh Python state.
TypeScript SDK only.

Pyodide does not provide isolation for hostile code. Host and network access
depend on the environment and configuration; see
[containment](https://docs.mirage.strukto.ai/typescript/runtime/pyodide.md#containment) before choosing it for
untrusted programs.

## Installation

```bash Node theme={null}
pnpm add @struktoai/mirage-node @struktoai/mirage-core pyodide
```

In a browser, install `@struktoai/mirage-browser` and `@struktoai/mirage-core`
instead: Pyodide loads from its CDN or `home`, not the `pyodide` package. The
page must be cross-origin isolated or registered with Mirage's service worker; see
[worker and browser setup](https://docs.mirage.strukto.ai/typescript/runtime/pyodide.md#worker-and-browser-setup).

## Usage

> [tab] TypeScript
>
> ```typescript theme={null}
> import { MountMode, RAMVFS, Workspace } from '@struktoai/mirage-node'
>
> const ws = new Workspace(
>   { '/data': new RAMVFS() },
>   { mode: MountMode.EXEC, machines: { py: { provider: 'in_process', runtime: 'pyodide' } } },
> )
> try {
>   const inline = await ws.shell("python3 -c 'print(1 + 1)'")
>   console.log(inline.stdoutText) // 2
>
>   await ws.shell(`echo 'import sys; print(sys.argv[1:])' > /data/hello.py`)
>   const script = await ws.shell('python3 /data/hello.py alice bob')
>   console.log(script.stdoutText) // ['alice', 'bob']
>
>   const piped = await ws.shell("echo 'print(1 + 1)' | python3")
>   console.log(piped.stdoutText) // 2
> } finally {
>   await ws.close()
> }
> ```

> [tab] YAML
>
> ```yaml theme={null}
> mode: exec
> machines:
>   py:
>     provider: in_process
>     runtime: pyodide
> mounts:
>   /data:
>     vfs: ram
> ```

## Packages

[Pyodide's packages](https://pyodide.org/en/stable/usage/packages-in-pyodide.html),
such as numpy, load when a program imports them. The first import downloads
the package from the Pyodide CDN; Node keeps it beside the installed
`pyodide` package for later runs.

| Config key | What it does |
| - | - |
| `packages` | Load these when each interpreter starts, before the program runs. |
| `auto_load_from_imports` | Load what a program imports. Default `true`; `false` loads only `packages`. |
| `deny_packages` | Never download these for an import. An import still works when the package is reachable another way, such as through `sys_path`. |
| `sys_path` | Mount paths to put first on `sys.path`: directories, globs, or pure-Python `.whl` files. |
| `package_base_url` | Where packages download from; point it at your own copy to work offline. |

> [tab] TypeScript
>
> ```typescript theme={null}
> import { MountMode, RAMVFS, Workspace } from '@struktoai/mirage-node'
> import { PyodideRuntime } from '@struktoai/mirage-core/runtime/python/pyodide'
>
> const runtime = new PyodideRuntime({
>   config: {
>     packages: ['numpy'],
>     denyPackages: ['requests'],
>     sysPath: ['/data/vendor', '/data/wheels/*.whl'],
>   },
> })
> const ws = new Workspace({ '/data': new RAMVFS() }, { mode: MountMode.EXEC, machines: { py: runtime } })
> ```

> [tab] YAML
>
> ```yaml theme={null}
> mode: exec
> machines:
>   py:
>     provider: in_process
>     runtime: pyodide
>     packages: [numpy]
>     deny_packages: [requests]
>     sys_path: [/data/vendor, /data/wheels/*.whl]
> mounts:
>   /data:
>     vfs: ram
> ```

A package from PyPI cannot be installed at run time: `micropip.install`
fails. Put its pure-Python wheel on a mount and list it in `sys_path`.

## Memory

`max_memory` caps the memory one run may grow to:

```yaml theme={null}
machines:
  py:
    provider: in_process
    runtime: pyodide
    max_memory: 256M
```

A run starts at about 50M. One that passes the cap fails with
`MemoryError`, and the next run starts fresh. Node stops the run when it
passes the cap; browsers check the cap when the run ends.

Without its own `max_memory`, a run may grow by what its workspace's
[`max_memory`](https://docs.mirage.strukto.ai/home/limits#memory) has left,
96 MB by default, past what the interpreter and its packages take to start.

## Python compatibility

Examples assume a writable `/data` mount. Mount modes and permissions still apply.

### `open()`

Modes and modifiers are listed separately; for example, `rb` combines `r`
and `b`. The file is read when it is opened.

| Mode or modifier | Support |
| - | - |
| `r` | ✓ |
| `w` | ✓ |
| `a` | ✓ |
| `x` | ✓ |
| `b` | ✓ |
| `t` | ✓ |
| `+` | ✓ |

> [accordion] Example: append to a workspace file
>
> ```python theme={null}
> with open("/data/log.txt", "a") as f:
>     f.write("Job completed.\n")
> ```

> [accordion] Limitations
>
> | API or behavior | Limitation |
> | - | - |
> | File access | Writes to workspace files follow mount permissions. Files created outside the mounts stay in memory and are lost when the run ends. |

### File objects

| API | Support |
| - | - |
| `f.read()` | ✓ |
| `f.write()` | ✓ |
| `f.truncate()` | ✓ |

> [accordion] Example: write, read and truncate a file
>
> ```python theme={null}
> with open("/data/example.txt", "w+") as f:
>     f.write("first\nsecond\n")
>     f.seek(0)
>     print(f.read(5))  # first
>     f.truncate(5)
> ```

> [accordion] Limitations
>
> | API or behavior | Limitation |
> | - | - |
> | `f.write()` | Written at close, or at the next call that reaches a mount. |

### `os`

#### File operations

| API | Support |
| - | - |
| `os.open()` | ✓ |
| `os.read()` | ✓ |
| `os.pread()` | ✓ |
| `os.write()` | ✓ |
| `os.pwrite()` | ✓ |
| `os.truncate()` | ✓ |
| `os.remove()` | ✓ |
| `os.unlink()` | ✓ |
| `os.rename()` | ✓ |
| `os.replace()` | ✓ |

#### Directory operations

| API | Support |
| - | - |
| `os.listdir()` | ✓ |
| `os.scandir()` | ✓ |
| `os.walk()` | ✓ |
| `os.mkdir()` | ✓ |
| `os.makedirs()` | ✓ |
| `os.rmdir()` | ✓ |

#### Metadata and links

| API | Support |
| - | - |
| `os.stat()` | ✓ |
| `os.lstat()` | ✓ |
| `os.fstat()` | ✓ |
| `os.symlink()` | ✓ |
| `os.readlink()` | ✓ |
| `os.utime()` | ✓ |
| `os.chmod()` | ✓ |
| `os.getxattr()` | ✓ |
| `os.setxattr()` | ✓ |
| `os.listxattr()` | ✓ |
| `os.removexattr()` | ✓ |

#### Environment and working directory

| API | Support |
| - | - |
| `os.getcwd()` | ✓ |
| `os.chdir()` | ✓ |
| `os.environ` | ✓ |

> [accordion] Example: list a workspace directory
>
> ```python theme={null}
> import os
>
> print(os.listdir("/data"))
> ```

> [accordion] Limitations
>
> | API or behavior | Limitation |
> | - | - |
> | `os.fsync()` | Accepted, but has no effect. |
> | `os.link()` | Does not exist. |
> | `os.open()` | The file is read when it is opened. |
> | `os.write()`, `os.pwrite()` | Written at close, or at the next call that reaches a mount. |
> | `os.rename()`, `os.replace()` | `EXDEV` across mounts, where `shutil.move` copies instead. |
> | `os.getxattr()`, `os.setxattr()`, `os.listxattr()`, `os.removexattr()` | The same attributes as `getfattr` in the shell. |
> | `os.getcwd()`, `os.chdir()` | The shell's working directory; a change lasts for the run. |
> | `os.environ` | The session's environment, never the host's. |

### `os.path`

| API | Support |
| - | - |
| `os.path` | ✓ |

> [accordion] Example: check a workspace path
>
> ```python theme={null}
> import os.path
>
> path = os.path.join("/data", "input.txt")
> print(os.path.exists(path))
> ```

### `pathlib`

| API | Support |
| - | - |
| `Path.stat()` | ✓ |
| `Path.glob()` | ✓ |
| `Path.unlink()` | ✓ |
| `Path.touch()` | ✓ |

> [accordion] Example: create and inspect a workspace file
>
> ```python theme={null}
> from pathlib import Path
>
> path = Path("/data/example.txt")
> path.write_text("hello\n")
> print(path.read_text())
> print(path.stat().st_size)
> ```

### `sys`

| API | Support |
| - | - |
| `sys.argv` | ✓ |
| `sys.stdin` | ✓ |

> [accordion] Example: read arguments and piped input
>
> ```python theme={null}
> import sys
>
> print(sys.argv[1:])
> print(sys.stdin.read())
> ```

### `time` and `datetime`

The clocks start at the workspace's [system time](https://docs.mirage.strukto.ai/home/configuration/workspace.md#system-time)
when it sets one, and files the program writes are stamped from the same
clock. `time.monotonic()` and `time.perf_counter()` measure elapsed time.

| API | Support |
| - | - |
| `time.time()`, `time.time_ns()` | ✓ |
| `time.localtime()`, `time.gmtime()`, `time.strftime()` | ✓ |
| `time.monotonic()`, `time.perf_counter()` | ✓ |
| `datetime.datetime.now()` | ✓ |
| `datetime.date.today()` | ✓ |

> [accordion] Example: print today's date
>
> ```python theme={null}
> import datetime
>
> print(datetime.date.today())
> ```

> [accordion] Limitations
>
> | API or behavior | Limitation |
> | - | - |
> | Local times | The session's `TZ`, UTC without one. `time.tzname` spells a zone as its offset, such as `UTC+0900`. |

### `json`

| API | Support |
| - | - |
| `json.load()` | ✓ |

> [accordion] Example: write and read workspace JSON
>
> ```python theme={null}
> import json
>
> with open("/data/result.json", "w") as f:
>     json.dump({"status": "done"}, f)
>
> with open("/data/result.json", "r") as f:
>     result = json.load(f)
> print(result["status"])  # done
> ```

### `glob`

| API | Support |
| - | - |
| `glob.glob()` | ✓ |

> [accordion] Example: find workspace text files
>
> ```python theme={null}
> import glob
>
> print(glob.glob("/data/*.txt"))
> ```

### `shutil`

| API | Support |
| - | - |
| `shutil.rmtree()` | ✓ |
| `shutil.move()` | ✓ |
| `shutil.which()` | ✓ |

* `shutil.which()`: Resolves executable names through Mirage's command lookup.

> [accordion] Example: move a workspace file
>
> ```python theme={null}
> import shutil
>
> with open("/data/draft.txt", "w") as f:
>     f.write("ready\n")
>
> shutil.move("/data/draft.txt", "/data/final.txt")
> ```

> [accordion] Limitations
>
> | API or behavior | Limitation |
> | - | - |
> | `shutil.move()` | Copies instead when a rename would cross mounts (`EXDEV`). |

### `subprocess`

| API | Support |
| - | - |
| `subprocess.run()` | ✓ |
| `subprocess.Popen()` | ✓ |

> [accordion] Example: run a Mirage command
>
> ```python theme={null}
> import subprocess
>
> result = subprocess.run(
>     ["ls", "/data"], capture_output=True, text=True, check=True
> )
> print(result.stdout)
> ```

> [accordion] Limitations
>
> | API or behavior | Limitation |
> | - | - |
> | `subprocess.run()`, `subprocess.Popen()` | Runs commands inside Mirage. Pending file writes are saved before the command starts. |
> | `Popen.send_signal()`, `terminate()`, `kill()` | Sends the signal as `kill` does. A command that ends on it reports a negative `returncode`. |

### Processes and signals

| API | Support |
| - | - |
| `os.getpid()`, `os.getppid()` | ✓ |
| `os.kill()`, `signal.raise_signal()` | ✓ |
| `signal.signal()` | ✓ |

> [accordion] Limitations
>
> | API or behavior | Limitation |
> | - | - |
> | `os.getpid()`, `os.getppid()` | Return the numbers `ps` and `$!` show. |
> | `os.kill()` | Reaches the program itself and the commands it started. Any other pid raises `ProcessLookupError`. |
> | `signal.signal()` | A handler runs when `kill` sends the signal. A program inside a file operation runs it when the operation ends. |

### `socket`

Network connections are unavailable in this runtime.

> [accordion] Limitations
>
> | API or behavior | Limitation |
> | - | - |
> | `socket` | Cannot connect (`ENETUNREACH`). |

### `mmap`

Unavailable in this runtime.

> [accordion] Limitations
>
> | API or behavior | Limitation |
> | - | - |
> | `mmap` | ✗ |

## Notes

Files written outside the mounts stay in memory and are lost when the run
ends.


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