CoolFace
Apppublic

sanjaymarathi/compicode-executor

sourceHugging Facemitupdated 6mo agoView on Hugging Face
0likes
executor.py220 linesDownload Raw Back to root
1import tempfile2import subprocess3import os4import time5import re6 7def execute_python(code: str, input_str: str) -> dict:8    start_time = time.time()9    temp_path = None10    try:11        with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False) as f:12            f.write(code)13            temp_path = f.name14        15        # Using subprocess.run with timeout16        process = subprocess.run(17            ['python', temp_path],18            input=input_str,19            text=True,20            capture_output=True,21            timeout=2.022        )23        runtime_ms = (time.time() - start_time) * 100024        25        return {26            "success": process.returncode == 0,27            "stdout": process.stdout,28            "stderr": process.stderr,29            "runtime_ms": int(runtime_ms)30        }31        32    except subprocess.TimeoutExpired:33        return {34            "success": False,35            "stdout": "",36            "stderr": "Execution Timeout (Over 2 seconds)",37            "runtime_ms": int((time.time() - start_time) * 1000)38        }39    except Exception as e:40        return {41            "success": False,42            "stdout": "",43            "stderr": str(e),44            "runtime_ms": 045        }46    finally:47        if temp_path and os.path.exists(temp_path):48            try:49                os.remove(temp_path)50            except OSError:51                pass52 53 54def execute_cpp(code: str, input_str: str) -> dict:55    start_time = time.time()56    temp_dir = tempfile.mkdtemp()57    source_path = os.path.join(temp_dir, 'main.cpp')58    binary_path = os.path.join(temp_dir, 'main.exe' if os.name == 'nt' else 'main')59    60    try:61        with open(source_path, 'w') as f:62            f.write(code)63        64        # Compile65        compile_proc = subprocess.run(66            ['g++', '-O2', source_path, '-o', binary_path],67            capture_output=True,68            text=True,69            timeout=5.070        )71        72        if compile_proc.returncode != 0:73            return {74                "success": False,75                "stdout": "",76                "stderr": f"Compilation Error:\n{compile_proc.stderr}",77                "runtime_ms": int((time.time() - start_time) * 1000)78            }79            80        exec_start = time.time()81        # Execute82        process = subprocess.run(83            [binary_path],84            input=input_str,85            text=True,86            capture_output=True,87            timeout=2.088        )89        runtime_ms = (time.time() - exec_start) * 100090        91        return {92            "success": process.returncode == 0,93            "stdout": process.stdout,94            "stderr": process.stderr,95            "runtime_ms": int(runtime_ms)96        }97    except subprocess.TimeoutExpired:98        return {99            "success": False,100            "stdout": "",101            "stderr": "Execution Timeout",102            "runtime_ms": int((time.time() - start_time) * 1000)103        }104    except Exception as e:105        return {106            "success": False,107            "stdout": "",108            "stderr": str(e),109            "runtime_ms": 0110        }111    finally:112        if os.path.exists(source_path):113            try:114                os.remove(source_path)115            except OSError:116                pass117        if os.path.exists(binary_path):118            try:119                os.remove(binary_path)120            except OSError:121                pass122        if os.path.exists(temp_dir):123            try:124                os.rmdir(temp_dir)125            except OSError:126                pass127 128 129def execute_java(code: str, input_str: str) -> dict:130    start_time = time.time()131    temp_dir = tempfile.mkdtemp()132    133    # Java single-file compilation requires the file to match the public class name134    class_match = re.search(r'class\s+([A-Za-z0-9_]+)', code)135    class_name = class_match.group(1) if class_match else "Main"136    source_path = os.path.join(temp_dir, f"{class_name}.java")137    138    try:139        with open(source_path, 'w') as f:140            f.write(code)141            142        # Compile143        compile_proc = subprocess.run(144            ['javac', source_path],145            capture_output=True, text=True, timeout=5.0146        )147        148        if compile_proc.returncode != 0:149            return {150                "success": False,151                "stdout": "",152                "stderr": f"Compilation Error:\n{compile_proc.stderr}",153                "runtime_ms": int((time.time() - start_time) * 1000)154            }155            156        exec_start = time.time()157        # Execute158        process = subprocess.run(159            ['java', '-cp', temp_dir, class_name],160            input=input_str,161            text=True,162            capture_output=True,163            timeout=3.0164        )165        runtime_ms = (time.time() - exec_start) * 1000166        167        return {168            "success": process.returncode == 0,169            "stdout": process.stdout,170            "stderr": process.stderr,171            "runtime_ms": int(runtime_ms)172        }173    except subprocess.TimeoutExpired:174        return {175            "success": False,176            "stdout": "",177            "stderr": "Execution Timeout",178            "runtime_ms": int((time.time() - start_time) * 1000)179        }180    except Exception as e:181        return {182            "success": False,183            "stdout": "",184            "stderr": str(e),185            "runtime_ms": 0186        }187    finally:188        if os.path.exists(source_path):189            try:190                os.remove(source_path)191            except OSError:192                pass193        class_file = os.path.join(temp_dir, f"{class_name}.class")194        if os.path.exists(class_file):195            try:196                os.remove(class_file)197            except OSError:198                pass199        if os.path.exists(temp_dir):200            try:201                os.rmdir(temp_dir)202            except OSError:203                pass204 205 206def execute_code(code: str, language: str, input_str: str) -> dict:207    if language.lower() == 'python':208        return execute_python(code, input_str)209    elif language.lower() in ['cpp', 'c++']:210        return execute_cpp(code, input_str)211    elif language.lower() == 'java':212        return execute_java(code, input_str)213    else:214        return {215            "success": False, 216            "stdout": "", 217            "stderr": f"Unsupported language: {language}", 218            "runtime_ms": 0219        }220