Skip to main content
PythonRuntime runs Python code in a Pyodide environment inside a Worker thread. It supports CPU time budgets and bidirectional data exchange through globals.

Creating a runtime

A PythonRuntime requires a system driver and a Pyodide runtime driver factory.
import { PythonRuntime, createPyodideRuntimeDriverFactory } from "@secure-exec/python";
import { createNodeDriver } from "@secure-exec/node";

const runtime = new PythonRuntime({
  systemDriver: createNodeDriver(),
  runtimeDriverFactory: createPyodideRuntimeDriverFactory(),
});
These exports are also available from "secure-exec" for backward compatibility.

exec vs run

Use exec() for side effects.
const result = await runtime.exec("print('hello from python')");
console.log(result.code); // 0
Use run() to get a value back. The last expression in the code is returned as value. You can also request specific globals.
const result = await runtime.run<number>("x = 40 + 2\nx", {
  globals: ["x"],
});
console.log(result.value);   // 42
console.log(result.globals);  // { x: 42 }

Capturing output

Same pattern as Node. Use the onStdio hook.
const logs: string[] = [];
await runtime.exec("print('hello')", {
  onStdio: (event) => logs.push(event.message),
});

Differences from Node runtime

  • No memoryLimit: Pyodide runs in a Worker thread, not a V8 isolate
  • No timingMitigation: not applicable to the Pyodide environment
  • run() returns value and globals instead of exports
  • Globals exchange lets you pass data into and out of the Python environment