My-AI-Assistant / code_executor.py
Ahmedoooooo's picture
Create code_executor.py
96428f4 verified
Raw
History Blame Contribute Delete
1.98 kB
# code_executor.py - تنفيذ آمن للأكواد
import subprocess
import tempfile
from pathlib import Path
BUNKER_AVAILABLE = False # لا نستخدم BunkerVM في Hugging Face
async def execute_code_safely(code: str, language: str = "python") -> str:
if language == "python":
return await _execute_python(code)
elif language == "javascript":
return await _execute_javascript(code)
else:
return f"⚠️ اللغة {language} غير مدعومة حالياً."
async def _execute_python(code: str) -> str:
try:
with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False) as f:
f.write(code)
temp_file = f.name
result = subprocess.run(['python', temp_file], capture_output=True, text=True, timeout=15)
Path(temp_file).unlink()
if result.returncode == 0:
return f"**✅ نتيجة التنفيذ:**\n```\n{result.stdout}\n```"
else:
return f"**❌ خطأ أثناء التنفيذ:**\n```\n{result.stderr}\n```"
except subprocess.TimeoutExpired:
return "⏰ تجاوز الوقت المسموح للتنفيذ (15 ثانية)."
except Exception as e:
return f"⚠️ خطأ غير متوقع: {e}"
async def _execute_javascript(code: str) -> str:
try:
with tempfile.NamedTemporaryFile(mode='w', suffix='.js', delete=False) as f:
f.write(code)
temp_file = f.name
result = subprocess.run(['node', temp_file], capture_output=True, text=True, timeout=15)
Path(temp_file).unlink()
if result.returncode == 0:
return f"**✅ نتيجة التنفيذ:**\n```\n{result.stdout}\n```"
else:
return f"**❌ خطأ في JavaScript:**\n```\n{result.stderr}\n```"
except FileNotFoundError:
return "⚠️ Node.js غير مثبت على النظام."
except Exception as e:
return f"⚠️ خطأ: {e}"