File size: 810 Bytes
1c7a9a0 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | import subprocess
from langchain.tools import tool
@tool(parse_docstring=True)
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}"
|