Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/wapython
Path: blob/main/python/python-wasm/src/browser.ts
1067 views
1
import { asyncKernel, FileSystemSpec } from "@cowasm/kernel";
2
import { Options, PythonWasmAsync } from "./common";
3
export type { Options, PythonWasmAsync };
4
5
import { fetchPackages } from "./packages";
6
import debug from "debug";
7
const log = debug("python-wasm");
8
9
import wasmUrl from "./python.wasm";
10
import pythonFull from "./python-stdlib.zip";
11
import pythonMinimal from "./python-minimal.zip";
12
import pythonReadline from "./python-readline.zip";
13
const PYTHONEXECUTABLE = "/usr/lib/python.wasm";
14
15
// We ONLY provide async version, since sync version isn't
16
// possible anymore since dynamic module loading has to be
17
// sync and browsers don't allow sync webassmbly loading.
18
export default async function asyncPython(
19
opts?: Options
20
): Promise<PythonWasmAsync> {
21
log("creating async CoWasm kernel...");
22
const fs = getFilesystem(opts);
23
log("fs = ", fs);
24
const kernel = await asyncKernel({
25
env: {
26
PYTHONHOME: "/usr",
27
PYTHONEXECUTABLE,
28
...opts?.env,
29
},
30
fs,
31
});
32
log("done");
33
log("fetching ", PYTHONEXECUTABLE);
34
await Promise.all([
35
kernel.waitUntilFsLoaded(),
36
37
kernel.fetch(wasmUrl, PYTHONEXECUTABLE),
38
39
// TODO: we have to await since once Python starts it synchronously takes over
40
// completely and rest of the fetches just can't finish. Longterm we'll use
41
// a completely different model for packages, of course.
42
fetchPackages(kernel),
43
]);
44
45
log("initializing python");
46
const python = new PythonWasmAsync(kernel, PYTHONEXECUTABLE);
47
await python.init();
48
49
log("done");
50
return python;
51
}
52
53
function getFilesystem(opts?: Options): FileSystemSpec[] {
54
// For ref, this is the not efficient version
55
// return [
56
// {
57
// type: "zipurl",
58
// zipurl: pythonFull,
59
// mountpoint: "/usr/lib/python3.11",
60
// },
61
// { type: "dev" },
62
// ];
63
64
return [
65
// This will result in synchronously loading a tiny filesystem needed for starting python interpreter.
66
{
67
type: "zipurl",
68
zipurl: opts?.noReadline ? pythonMinimal : pythonReadline,
69
mountpoint: "/usr/lib/python3.11",
70
},
71
{ type: "dev" },
72
// Load full stdlib python filesystem asynchronously. Only needed to run actual interesting code.
73
// This way can load the wasm file from disk at the same time as the stdlib.
74
{
75
type: "zipurl",
76
async: true,
77
zipurl: pythonFull,
78
mountpoint: "/usr/lib/python3.11",
79
},
80
];
81
}
82
83