from http.server import HTTPServer, BaseHTTPRequestHandler import subprocess import socket import psutil import os,signal class MyHandler(BaseHTTPRequestHandler): def do_POST(self): if self.path == '/run_code': # Read the POST data containing the code to run content_length = int(self.headers['Content-Length']) code = self.rfile.read(content_length).decode('utf-8') with open('program.py', 'w') as f: f.write(code) command = "python program.py" def run_process(): try: process = subprocess.Popen( command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, # stdin=subprocess.PIPE, text=True, bufsize=1, # Line buffered universal_newlines=True, shell=True ) line_count = 0 for line in iter(process.stdout.readline, ''): if line_count <5: line_count+=1 yield f'data: {line.strip()}\n\n' else: yield f'data: error:infinite loop detect\n\n' os.kill(int(process.pid), signal.CTRL_C_EVENT) for line in iter(process.stderr.readline, ''): yield f'data: error:{line.strip()}\n\n' # process.communicate() error_message = process.stderr.read() output, error = process.communicate() if process.returncode == 0: pass # yield 'data: Code executed successfully\n\n' else: yield f'data: error:Execution failed with return code {process.returncode}\n\n' except Exception as e: yield f'data: error: {str(e)}\n\n' yield f'data: error:process terminated\n\n' self.send_response(200) self.send_header('Content-type', 'text/event-stream') self.send_header('Cache-Control', 'no-cache') self.send_header('Connection', 'keep-alive') self.end_headers() for chunk in run_process(): self.wfile.write(chunk.encode('utf-8')) # Close the connection explicitly self.wfile.write(b'event: end\n\n') self.wfile.flush() self.connection.shutdown(socket.SHUT_RDWR) self.connection.close() else: self.send_response(404) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(b'404: Not Found') # Create an HTTP server and bind it to a specific host and port httpd = HTTPServer(('0.0.0.0', 7860), MyHandler) # Start serving indefinitely httpd.serve_forever()