Spaces:
Runtime error
Runtime error
Create executor.py
Browse files- executor.py +32 -0
executor.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import subprocess
|
| 2 |
+
import os
|
| 3 |
+
import tempfile
|
| 4 |
+
|
| 5 |
+
class Executor:
|
| 6 |
+
def execute_code(self, code):
|
| 7 |
+
try:
|
| 8 |
+
# Save code to temporary file
|
| 9 |
+
with tempfile.NamedTemporaryFile(suffix=".py", delete=False, mode="w") as temp_file:
|
| 10 |
+
temp_file.write(code)
|
| 11 |
+
temp_file_path = temp_file.name
|
| 12 |
+
|
| 13 |
+
# Execute the code
|
| 14 |
+
result = subprocess.run(
|
| 15 |
+
["python", temp_file_path],
|
| 16 |
+
capture_output=True,
|
| 17 |
+
text=True,
|
| 18 |
+
timeout=30
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
# Clean up
|
| 22 |
+
os.unlink(temp_file_path)
|
| 23 |
+
|
| 24 |
+
if result.returncode == 0:
|
| 25 |
+
return result.stdout.strip() or "Code executed successfully"
|
| 26 |
+
else:
|
| 27 |
+
return f"Error: {result.stderr.strip() or 'Unknown error'}"
|
| 28 |
+
|
| 29 |
+
except subprocess.TimeoutExpired:
|
| 30 |
+
return "Error: Code execution timed out"
|
| 31 |
+
except Exception as e:
|
| 32 |
+
return f"Execution error: {str(e)}"
|