Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/wapython
Path: blob/main/web/browser/src/python.ts
1067 views
1
// Load Python kernel in the browser
2
3
import pythonWasm from "python-wasm";
4
import debug from "debug";
5
const log = debug("browser:python");
6
7
export default async function main() {
8
log("call python init");
9
// noReadline saves a tiny amount of space; no terminal here so no need for readline
10
const t0 = new Date().valueOf();
11
const python = await pythonWasm({ noReadline: true });
12
const tm = new Date().valueOf() - t0;
13
log("loaded python");
14
(window as any).python = python;
15
console.log("set window.python");
16
const { exec, repr } = python;
17
log(await repr("2+3"));
18
19
const element = document.createElement("pre");
20
21
// load something nontrivial (a dynamic library) from the standard library:
22
await exec("import sqlite3");
23
log(await repr("sqlite3"));
24
25
// Run some code in Python that defines variables n and s.
26
await exec("from random import randint; n = randint(0,10**6)");
27
log("computed n = ", await repr("n"));
28
await exec("s = sum(range(n))");
29
await exec("import sys");
30
// Use repr to get their string representation:
31
element.innerHTML = `Load/startup time: ${tm}ms\n\n${await repr(
32
"sys.version"
33
)}\n\nLet's do some math!\n\n1 + 2 + 3 + ... + ${await repr(
34
"n"
35
)} = ${await repr("s")}`;
36
37
// do something with a little in memory table:
38
const sql = `
39
import sqlite3
40
con = sqlite3.connect(":memory:")
41
cur = con.cursor()
42
cur.execute("CREATE TABLE movies(title, year, score)")
43
cur.execute("INSERT INTO movies values('Red Dawn',1984,50)")
44
cur.execute("INSERT INTO movies values('Red Dawn',2012,15)")
45
res = cur.execute("SELECT * FROM movies")
46
`;
47
await exec(sql);
48
element.innerHTML += `<br/><pre>\nHow about some SQL?\n${sql}</pre><br/>${await repr(
49
"list(res)"
50
)}`;
51
document.body.appendChild(element);
52
}
53
54