Update interpreter.py
Browse files- interpreter.py +27 -0
interpreter.py
CHANGED
|
@@ -1,14 +1,40 @@
|
|
| 1 |
import io
|
| 2 |
import sys
|
|
|
|
| 3 |
from logger import logger
|
| 4 |
|
| 5 |
def run_code(code):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
# Redirect stdout to capture code output
|
| 7 |
old_stdout = sys.stdout
|
| 8 |
redirected_output = sys.stdout = io.StringIO()
|
| 9 |
|
| 10 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
exec(code)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
except Exception as e:
|
| 13 |
logger.error(f"Execution error: {e}")
|
| 14 |
return f"Error: {e}"
|
|
@@ -16,4 +42,5 @@ def run_code(code):
|
|
| 16 |
# Reset stdout
|
| 17 |
sys.stdout = old_stdout
|
| 18 |
|
|
|
|
| 19 |
return redirected_output.getvalue()
|
|
|
|
| 1 |
import io
|
| 2 |
import sys
|
| 3 |
+
import ast
|
| 4 |
from logger import logger
|
| 5 |
|
| 6 |
def run_code(code):
|
| 7 |
+
"""
|
| 8 |
+
Executes user-provided Python code and captures its output.
|
| 9 |
+
Detects function definitions and provides feedback if functions are not invoked.
|
| 10 |
+
|
| 11 |
+
Parameters:
|
| 12 |
+
code (str): Python code entered by the user.
|
| 13 |
+
|
| 14 |
+
Returns:
|
| 15 |
+
str: Captured output or error messages.
|
| 16 |
+
"""
|
| 17 |
# Redirect stdout to capture code output
|
| 18 |
old_stdout = sys.stdout
|
| 19 |
redirected_output = sys.stdout = io.StringIO()
|
| 20 |
|
| 21 |
try:
|
| 22 |
+
# Parse the code to detect function definitions
|
| 23 |
+
tree = ast.parse(code)
|
| 24 |
+
function_names = [
|
| 25 |
+
node.name for node in ast.walk(tree) if isinstance(node, ast.FunctionDef)
|
| 26 |
+
]
|
| 27 |
+
|
| 28 |
+
# Execute the code
|
| 29 |
exec(code)
|
| 30 |
+
|
| 31 |
+
# Check if functions are defined but not called
|
| 32 |
+
if function_names:
|
| 33 |
+
captured_output = redirected_output.getvalue()
|
| 34 |
+
captured_output += f"\n\nDefined functions: {', '.join(function_names)}\n"
|
| 35 |
+
captured_output += "Note: Functions need to be explicitly called to see their output."
|
| 36 |
+
return captured_output
|
| 37 |
+
|
| 38 |
except Exception as e:
|
| 39 |
logger.error(f"Execution error: {e}")
|
| 40 |
return f"Error: {e}"
|
|
|
|
| 42 |
# Reset stdout
|
| 43 |
sys.stdout = old_stdout
|
| 44 |
|
| 45 |
+
# Return the captured output
|
| 46 |
return redirected_output.getvalue()
|