MCPcopy Create free account
hub / github.com/astral-sh/ruff / runPython

Function runPython

playground/ty/src/Editor/runPython.ts:6–64  ·  view source on GitHub ↗
(workspace: SerializedFiles)

Source from the content-addressed store, hash-verified

4const SANDBOX_BASE_DIRECTORY = "/playground/";
5
6export async function runPython(workspace: SerializedFiles): Promise<string> {
7 let combinedOutput = "";
8
9 const outputHandler = (output: string) => {
10 combinedOutput += output + "\n";
11 };
12
13 try {
14 const pyodide = await loadPyodide({
15 env: {
16 HOME: SANDBOX_BASE_DIRECTORY,
17 },
18 });
19
20 pyodide.setStdout({ batched: outputHandler });
21 pyodide.setStderr({ batched: outputHandler });
22
23 for (const [fileName, content] of Object.entries(workspace.files)) {
24 const lastSeparator = fileName.lastIndexOf("/");
25
26 if (lastSeparator !== -1) {
27 const directory =
28 SANDBOX_BASE_DIRECTORY + fileName.slice(0, lastSeparator);
29 pyodide.FS.mkdirTree(directory);
30 }
31
32 pyodide.FS.writeFile(SANDBOX_BASE_DIRECTORY + fileName, content);
33 }
34
35 const dict = pyodide.globals.get("dict");
36 const globals = dict();
37
38 // Patch `reveal_type` to print runtime values
39 try {
40 pyodide.runPython(`
41 import builtins
42
43 def reveal_type(obj):
44 import typing
45 print(f"Runtime value is '{obj}'")
46 return typing.reveal_type(obj)
47
48 builtins.reveal_type = reveal_type`);
49
50 pyodide.runPython(workspace.files[workspace.current] ?? "", {
51 globals,
52 locals: globals,
53 filename: workspace.current,
54 });
55 } finally {
56 globals.destroy();
57 dict.destroy();
58 }
59
60 return combinedOutput;
61 } catch (error) {
62 return `Failed to run Python script: ${error}`;
63 }

Callers 1

PlaygroundFunction · 0.90

Calls 3

entriesMethod · 0.45
sliceMethod · 0.45
getMethod · 0.45

Tested by

no test coverage detected