abyss-api / agent /tools /code_runner.py
KyleEastwood's picture
Upload folder using huggingface_hub
cc15101 verified
Raw History Blame Contribute Delete
799 Bytes
import os
import subprocess
import tempfile
TIMEOUT = 5 # SECONDS
def run_code(code: str) -> str:
try:
with tempfile.NamedTemporaryFile(suffix=".py", mode="w", delete=False) as f:
f.write(code)
path = f.name
result = subprocess.run(
["python", path],
capture_output=True,
text=True,
timeout=TIMEOUT,
)
os.unlink(path)
stdout = result.stdout.strip()
stderr = result.stderr.strip()
if stderr:
return f"stdout: {stdout}\nstderr: {stderr}"
return stdout or "(no output)"
except subprocess.TimeoutExpired:
return f"Timed out after {TIMEOUT}s"
except Exception as e:
return f"Code runner error: {e}"