Download tools/execute_code.py from andrei-sferdian/Agents_Course_Final_Assignment: direct link, hf CLI and curl.
- Browser
- Download file 810 Bytes
-
https://huggingface.co/spaces/andrei-sferdian/Agents_Course_Final_Assignment/resolve/main/tools/execute_code.py
- Command line
-
hf download hf://spaces/andrei-sferdian/Agents_Course_Final_Assignment/tools/execute_code.py
-
curl -L -o execute_code.py https://huggingface.co/spaces/andrei-sferdian/Agents_Course_Final_Assignment/resolve/main/tools/execute_code.py
810 Bytes
| import subprocess | |
| from langchain.tools import tool | |
| def execute_python_code(code: str) -> str: | |
| """ | |
| Executes a given Python code snippet in a subprocess and returns its output. | |
| Args: | |
| code (str): The Python code to execute as a string. | |
| Returns: | |
| str: The standard output of the executed code if successful, or an error message | |
| containing the standard error output if the execution fails. | |
| Raises: | |
| None: Any exceptions during execution are caught and handled internally. | |
| """ | |
| try: | |
| process = subprocess.run( | |
| ["python3", "-c", code], text=True, capture_output=True, check=True | |
| ) | |
| return process.stdout | |
| except subprocess.CalledProcessError as e: | |
| return f"Error: {e.stderr}" | |