Download interpreter.py from Canstralian/Python_Code_Assistance: direct link, hf CLI and curl.
- Browser
- Download file 1.49 kB
-
https://huggingface.co/spaces/Canstralian/Python_Code_Assistance/resolve/aebf99100f8b61291f6f6b37d620d4e8f0406e13/interpreter.py
- Command line
-
hf download hf://spaces/Canstralian/Python_Code_Assistance@aebf99100f8b61291f6f6b37d620d4e8f0406e13/interpreter.py
-
curl -L -o interpreter.py https://huggingface.co/spaces/Canstralian/Python_Code_Assistance/resolve/aebf99100f8b61291f6f6b37d620d4e8f0406e13/interpreter.py
1.49 kB
| 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. | |
| """ | |
| # Redirect stdout to capture code output | |
| old_stdout = sys.stdout | |
| redirected_output = sys.stdout = io.StringIO() | |
| # Create a dedicated execution namespace | |
| exec_globals = {} | |
| try: | |
| # Parse the code to detect function definitions | |
| tree = ast.parse(code) | |
| function_names = [ | |
| node.name for node in ast.walk(tree) if isinstance(node, ast.FunctionDef) | |
| ] | |
| # Execute the code in the dedicated namespace | |
| exec(code, exec_globals) | |
| # Check if functions are defined but not called | |
| 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: | |
| # Reset stdout | |
| sys.stdout = old_stdout | |
| # Return the captured output | |
| return redirected_output.getvalue() | |