-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscripting.py
More file actions
38 lines (33 loc) · 958 Bytes
/
scripting.py
File metadata and controls
38 lines (33 loc) · 958 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
"""
scripting.py
Execute Python scripts in a restricted environment.
"""
import io
import contextlib
def run_script(script: str) -> str:
"""
Executes a Python script within a restricted environment.
Args:
script (str): Python code to execute.
Returns:
str: The output or error of the script execution.
"""
# Redirect stdout and stderr to capture output
output = io.StringIO()
restricted_globals = {
"__builtins__": {
"print": print,
"range": range,
"len": len,
"str": str,
"int": int,
"__import__": __import__,
}
}
restricted_locals = {}
try:
with contextlib.redirect_stdout(output), contextlib.redirect_stderr(output):
exec(script, restricted_globals, restricted_locals)
except Exception as e:
return f"Error during execution: {e}"
return output.getvalue()