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