-
Notifications
You must be signed in to change notification settings - Fork 893
Expand file tree
/
Copy pathcode_exec.py
More file actions
39 lines (30 loc) · 955 Bytes
/
code_exec.py
File metadata and controls
39 lines (30 loc) · 955 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
from e2b import Sandbox
def print_out(output):
print(output.line)
# 1. Start the playground sandbox
sandbox = Sandbox(
# You can pass your own sandbox template id
template="base",
auto_pause=True,
)
# 2. Save the JavaScript code to a file inside the playground
code = """
const fs = require('fs');
const dirContent = fs.readdirSync('/');
dirContent.forEach((item) => {
console.log('Root dir item inside playground:', item);
});
"""
sandbox.filesystem.write("/code/index.js", code)
# 3. Start the execution of the JavaScript file we saved
proc = sandbox.process.start( # $HighlightLine
cmd="node /code/index.js", # $HighlightLine
# 4. Stream stdout, stderr
on_stdout=print_out, # $HighlightLine
on_stderr=print_out, # $HighlightLine
) # $HighlightLine
# 4. Wait for the process to finish
proc.wait()
# 5. Or you can access output after the process has finished
output = proc.output
sandbox.close()