CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
sagemathinc

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/jupyter/stateless-api/execute.ts
Views: 687
1
/*
2
~/cocalc/src/packages/project$ node
3
Welcome to Node.js v16.19.1.
4
Type ".help" for more information.
5
> e = require('./dist/jupyter/stateless-api/kernel').default; z = await e.getFromPool('python3'); await z.execute("2+3")
6
[ { data: { 'text/plain': '5' } } ]
7
>
8
*/
9
10
import { jupyter_execute_response } from "@cocalc/util/message";
11
import Kernel from "./kernel";
12
import getLogger from "@cocalc/backend/logger";
13
const log = getLogger("jupyter:stateless-api:execute");
14
15
export default async function jupyterExecute(socket, mesg) {
16
log.debug(mesg);
17
let kernel: undefined | Kernel = undefined;
18
try {
19
kernel = await Kernel.getFromPool(mesg.kernel, mesg.pool);
20
const outputs: object[] = [];
21
22
if (mesg.path != null) {
23
try {
24
await kernel.chdir(mesg.path);
25
log.debug("successful chdir");
26
} catch (err) {
27
outputs.push({ name: "stderr", text: `${err}` });
28
log.debug("chdir failed", err);
29
}
30
}
31
32
if (mesg.history != null && mesg.history.length > 0) {
33
// just execute this directly, since we will ignore the output
34
log.debug("evaluating history");
35
await kernel.execute(mesg.history.join("\n"), mesg.limits);
36
}
37
38
// append the output of running mesg.input to outputs:
39
for (const output of await kernel.execute(mesg.input, mesg.limits)) {
40
outputs.push(output);
41
}
42
socket.write_mesg(
43
"json",
44
jupyter_execute_response({ id: mesg.id, output: outputs })
45
);
46
} finally {
47
if (kernel) {
48
await kernel.close();
49
}
50
}
51
}
52
53