0
# Runtime Loading
1
2
The runtime loading system provides comprehensive control over how Pyodide initializes, including package loading, environment configuration, and file system setup.
3
4
## Loading the Runtime
5
6
### loadPyodide
7
8
Load and initialize the Pyodide WebAssembly runtime with configurable options.
9
10
```javascript { .api }
11
function loadPyodide(options?: {
12
indexURL?: string;
13
packageCacheDir?: string;
14
lockFileURL?: string;
15
lockFileContents?: Lockfile | string | Promise<Lockfile | string>;
16
packageBaseUrl?: string;
17
fullStdLib?: boolean;
18
stdLibURL?: string;
19
stdin?: () => string;
20
stdout?: (msg: string) => void;
21
stderr?: (msg: string) => void;
22
jsglobals?: object;
23
_sysExecutable?: string;
24
args?: string[];
25
env?: { [key: string]: string };
26
packages?: string[];
27
pyproxyToStringRepr?: boolean;
28
enableRunUntilComplete?: boolean;
29
checkAPIVersion?: boolean;
30
fsInit?: (FS: FSType, info: { sitePackages: string }) => Promise<void>;
31
convertNullToNone?: boolean;
32
_makeSnapshot?: boolean;
33
_loadSnapshot?: Uint8Array | ArrayBuffer | PromiseLike<Uint8Array | ArrayBuffer>;
34
_snapshotDeserializer?: (obj: any) => any;
35
}): Promise<PyodideAPI>;
36
```
37
38
**Parameters:**
39
- `indexURL` - URL for Pyodide runtime files (default: auto-detected from script location)
40
- `packageCacheDir` - Directory for package caching in Node.js (default: same as indexURL)
41
- `lockFileURL` - URL for pyodide-lock.json (default: `${indexURL}/pyodide-lock.json`)
42
- `lockFileContents` - Direct lock file contents instead of URL
43
- `packageBaseUrl` - Base URL for relative package paths
44
- `fullStdLib` - Load complete Python standard library (default: false)
45
- `stdLibURL` - URL for python_stdlib.zip (default: `${indexURL}/python_stdlib.zip`)
46
- `stdin` - Standard input callback function
47
- `stdout` - Standard output callback function
48
- `stderr` - Standard error callback function
49
- `jsglobals` - Object to use as JavaScript globals in Python (default: globalThis)
50
- `args` - Command line arguments for Python (default: [])
51
- `env` - Environment variables for Python (default: {})
52
- `packages` - Packages to load during initialization
53
- `pyproxyToStringRepr` - **@deprecated** Use old behavior where PyProxy.toString() calls repr() instead of str() (default: false)
54
- `enableRunUntilComplete` - Enable loop.run_until_complete() with stack switching (default: true)
55
- `checkAPIVersion` - Verify API version compatibility (default: true)
56
- `convertNullToNone` - **@deprecated** Use old behavior where JavaScript null converts to None instead of jsnull (default: false)
57
- `fsInit` - File system initialization hook
58
59
**Returns:** Promise resolving to PyodideAPI instance
60
61
## Usage Examples
62
63
### Basic Loading
64
65
```javascript
66
import { loadPyodide } from "pyodide";
67
68
const pyodide = await loadPyodide();
69
console.log("Pyodide loaded successfully");
70
```
71
72
### Custom Configuration
73
74
```javascript
75
import { loadPyodide } from "pyodide";
76
77
const pyodide = await loadPyodide({
78
indexURL: "https://cdn.jsdelivr.net/pyodide/v0.28.2/full/",
79
fullStdLib: true,
80
packages: ["numpy", "pandas"],
81
stdout: (msg) => console.log(`Python: ${msg}`),
82
stderr: (msg) => console.error(`Python Error: ${msg}`),
83
env: {
84
"PYTHONPATH": "/custom/path",
85
"MY_VAR": "custom_value"
86
},
87
args: ["-u", "-W", "ignore"]
88
});
89
```
90
91
### Node.js with Package Caching
92
93
```javascript
94
import { loadPyodide } from "pyodide";
95
import path from "path";
96
97
const pyodide = await loadPyodide({
98
packageCacheDir: path.join(process.cwd(), "pyodide_cache"),
99
packages: ["scipy", "matplotlib"],
100
stdout: (msg) => process.stdout.write(msg + "\n"),
101
stderr: (msg) => process.stderr.write(msg + "\n")
102
});
103
```
104
105
### Custom Lock File
106
107
```javascript
108
import { loadPyodide } from "pyodide";
109
110
const customLockFile = {
111
info: {
112
arch: "wasm32",
113
platform: "emscripten_3_1_27",
114
version: "0.28.2",
115
python: "3.12.1"
116
},
117
packages: {
118
// custom package definitions
119
}
120
};
121
122
const pyodide = await loadPyodide({
123
lockFileContents: customLockFile,
124
packageBaseUrl: "https://custom-cdn.example.com/packages/"
125
});
126
```
127
128
### File System Initialization
129
130
```javascript
131
import { loadPyodide } from "pyodide";
132
133
const pyodide = await loadPyodide({
134
fsInit: async (FS, { sitePackages }) => {
135
// Create custom directories
136
FS.mkdir("/workspace");
137
FS.mkdir("/data");
138
139
// Write initial files
140
FS.writeFile("/workspace/config.py", "DEBUG = True");
141
142
console.log(`Site packages located at: ${sitePackages}`);
143
}
144
});
145
```
146
147
### Snapshot Loading (Advanced)
148
149
```javascript
150
import { loadPyodide } from "pyodide";
151
152
// Load from a pre-created snapshot for faster startup
153
const snapshotData = await fetch("./pyodide-snapshot.dat")
154
.then(r => r.arrayBuffer());
155
156
const pyodide = await loadPyodide({
157
_loadSnapshot: snapshotData,
158
_snapshotDeserializer: (obj) => {
159
// Custom deserialization logic
160
return obj;
161
}
162
});
163
```
164
165
## Configuration Types
166
167
```javascript { .api }
168
interface FSType {
169
readFile(path: string, options?: { encoding?: string }): string | Uint8Array;
170
writeFile(path: string, data: string | ArrayBufferView): void;
171
mkdir(path: string): void;
172
// ... additional Emscripten FS methods
173
}
174
175
interface Lockfile {
176
info: LockfileInfo;
177
packages: { [name: string]: LockfilePackage };
178
}
179
180
interface LockfileInfo {
181
arch: string;
182
platform: string;
183
version: string;
184
python: string;
185
}
186
187
interface LockfilePackage {
188
name: string;
189
version: string;
190
file_name: string;
191
install_dir: string;
192
sha256: string;
193
imports: string[];
194
depends: string[];
195
package_type: string;
196
}
197
```
198
199
## Error Handling
200
201
```javascript
202
try {
203
const pyodide = await loadPyodide({
204
indexURL: "https://invalid-url.com/pyodide/"
205
});
206
} catch (error) {
207
if (error.message.includes("Failed to fetch")) {
208
console.error("Network error loading Pyodide");
209
} else if (error.message.includes("version does not match")) {
210
console.error("API version mismatch");
211
} else {
212
console.error("Unknown error:", error);
213
}
214
}
215
```
216
217
## Version Information
218
219
Access the Pyodide version after loading:
220
221
```javascript
222
import { loadPyodide, version } from "pyodide";
223
224
console.log(`Loading Pyodide version: ${version}`);
225
const pyodide = await loadPyodide();
226
console.log(`Loaded Pyodide version: ${pyodide.version}`);
227
```