|
import io |
|
import sys |
|
import ast |
|
from logger import logger |
|
|
|
def run_code(code): |
|
""" |
|
Executes user-provided Python code and captures its output. |
|
Detects function definitions and provides feedback if functions are not invoked. |
|
|
|
Parameters: |
|
code (str): Python code entered by the user. |
|
|
|
Returns: |
|
str: Captured output or error messages. |
|
""" |
|
|
|
old_stdout = sys.stdout |
|
redirected_output = sys.stdout = io.StringIO() |
|
|
|
|
|
exec_globals = {} |
|
|
|
try: |
|
|
|
tree = ast.parse(code) |
|
function_names = [ |
|
node.name for node in ast.walk(tree) if isinstance(node, ast.FunctionDef) |
|
] |
|
|
|
|
|
exec(code, exec_globals) |
|
|
|
|
|
if function_names: |
|
captured_output = redirected_output.getvalue() |
|
captured_output += f"\n\nDefined functions: {', '.join(function_names)}\n" |
|
captured_output += "Note: Functions need to be explicitly called to see their output." |
|
return captured_output |
|
|
|
except Exception as e: |
|
logger.error(f"Execution error: {e}") |
|
return f"Error: {e}" |
|
finally: |
|
|
|
sys.stdout = old_stdout |
|
|
|
|
|
return redirected_output.getvalue() |
|
|