Skip to content

Commit

Permalink
Fixes Python print()s not showing up in wrangler dev.
Browse files Browse the repository at this point in the history
  • Loading branch information
dom96 committed Feb 14, 2025
1 parent 1ad8f4c commit 6571e6b
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/pyodide/internal/python.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,5 +102,18 @@ export async function loadPyodide(
const pyodide = Module.API.public_api;

finishSnapshotSetup(pyodide);

Module.API.initializeStreams();

// Need to set these here so that the logs go to the right context. If we don't they will go
// to SetupEmscripten's context and end up being KJ_LOG'd, which we do not want.
pyodide.setStdout({
batched: (msg: any) => console.log(msg),
});

pyodide.setStderr({
batched: (msg: any) => console.error(msg),
});

return pyodide;
}
2 changes: 2 additions & 0 deletions src/pyodide/types/Pyodide.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,6 @@ interface Pyodide {
FS: FS;
site_packages: string;
loadPackage: (names: string | string[], options: object) => Promise<any[]>;
setStdout: (options?: any) => void;
setStderr: (options?: any) => void;
}
13 changes: 13 additions & 0 deletions src/pyodide/types/emscripten.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,24 @@ interface PyodideConfig {
indexURL?: string;
}

type InFuncType = () =>
| null
| undefined
| string
| ArrayBuffer
| Uint8Array
| number;

interface API {
config: PyodideConfig;
finalizeBootstrap: () => void;
public_api: Pyodide;
rawRun: (code: string) => [status: number, err: string];
initializeStreams: (
stdin?: InFuncType,
stdout?: (a: string) => void,
stderr?: (a: string) => void
) => void;
}

interface LDSO {
Expand Down
2 changes: 2 additions & 0 deletions src/workerd/server/tests/python/hello/worker.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
def test():
from js import console
from js.WebAssembly import Suspending

Suspending # noqa: B018
Expand All @@ -7,3 +8,4 @@ def test():
# because we don't test whether we printed anything.
# TODO: update this to test that something happened
print("Does this work?")
console.log("Does this work?") # both should print the same output

0 comments on commit 6571e6b

Please sign in to comment.