fix: execute js/py code (#129)
This commit is contained in:
@@ -12,8 +12,11 @@ exports.run = function run({ code }) {
|
|||||||
if (callback) callback();
|
if (callback) callback();
|
||||||
};
|
};
|
||||||
|
|
||||||
eval(code);
|
const value = eval(code);
|
||||||
|
if (value !== undefined) {
|
||||||
|
output += value;
|
||||||
|
}
|
||||||
|
|
||||||
process.stdout.write = oldStdoutWrite;
|
process.stdout.write = oldStdoutWrite;
|
||||||
return output;
|
return output;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,16 +1,33 @@
|
|||||||
|
import ast
|
||||||
import io
|
import io
|
||||||
import sys
|
from contextlib import redirect_stdout
|
||||||
|
|
||||||
|
|
||||||
def run(code: str):
|
def run(code: str):
|
||||||
"""Execute the python code.
|
"""Execute the python code.
|
||||||
Args:
|
Args:
|
||||||
code: Python code to execute, such as `print("hello world")`
|
code: Python code to execute, such as `print("hello world")`
|
||||||
"""
|
"""
|
||||||
old_stdout = sys.stdout
|
|
||||||
output = io.StringIO()
|
output = io.StringIO()
|
||||||
sys.stdout = output
|
with redirect_stdout(output):
|
||||||
|
value = exec_with_return(code, {}, {})
|
||||||
|
|
||||||
exec(code)
|
if value is not None:
|
||||||
|
output.write(str(value))
|
||||||
|
|
||||||
sys.stdout = old_stdout
|
return output.getvalue()
|
||||||
return output.getvalue()
|
|
||||||
|
|
||||||
|
def exec_with_return(code: str, globals: dict, locals: dict):
|
||||||
|
a = ast.parse(code)
|
||||||
|
last_expression = None
|
||||||
|
if a.body:
|
||||||
|
if isinstance(a_last := a.body[-1], ast.Expr):
|
||||||
|
last_expression = ast.unparse(a.body.pop())
|
||||||
|
elif isinstance(a_last, ast.Assign):
|
||||||
|
last_expression = ast.unparse(a_last.targets[0])
|
||||||
|
elif isinstance(a_last, (ast.AnnAssign, ast.AugAssign)):
|
||||||
|
last_expression = ast.unparse(a_last.target)
|
||||||
|
exec(ast.unparse(a), globals, locals)
|
||||||
|
if last_expression:
|
||||||
|
return eval(last_expression, globals, locals)
|
||||||
|
|||||||
Reference in New Issue
Block a user