Spaces:
Sleeping
Sleeping
import socket | |
from http.server import HTTPServer, BaseHTTPRequestHandler | |
import subprocess | |
import re | |
import threading | |
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_to_run = self.rfile.read(content_length).decode('utf-8') | |
# Create a socket for communication with the client | |
client_socket, address = self.server.client_listener.accept() | |
# Run the code | |
def run_process(): | |
try: | |
process = subprocess.Popen( | |
['python', '-c', code_to_run], | |
stdin=subprocess.PIPE, | |
stdout=subprocess.PIPE, | |
stderr=subprocess.PIPE, | |
text=True, | |
bufsize=1, # Line buffered | |
universal_newlines=True, | |
shell=True # Allow running shell commands | |
) | |
while True: | |
line = process.stdout.readline() | |
if not line: | |
break | |
# Send SSE event for each line in the output | |
client_socket.send(f'data: {line.strip()}\n\n'.encode('utf-8')) | |
# If 'event: input' is received, wait for input from the client | |
if 'event: input' in line: | |
user_input = client_socket.recv(1024).decode('utf-8') | |
process.stdin.write(user_input + '\n') | |
process.stdin.flush() | |
process.communicate() | |
if process.returncode == 0: | |
client_socket.send(b'data: Code executed successfully\n\n') | |
else: | |
error_message = process.stderr.read() | |
client_socket.send(f'data: Error: {error_message}\n\n'.encode('utf-8')) | |
except Exception as e: | |
client_socket.send(f'data: Error: {str(e)}\n\n'.encode('utf-8')) | |
# Send a specific SSE message to indicate the end of the process | |
client_socket.send(b'event: end\ndata: Process complete\n\n') | |
# Close the connection explicitly | |
client_socket.close() | |
threading.Thread(target=run_process).start() | |
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() | |
else: | |
self.send_response(404) | |
self.send_header('Content-type', 'text/html') | |
self.end_headers() | |
self.wfile.write(b'404: Not Found') | |
class MyServer(HTTPServer): | |
def __init__(self, server_address, RequestHandlerClass, bind_and_activate=True): | |
super().__init__(server_address, RequestHandlerClass, bind_and_activate) | |
self.client_listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
self.client_listener.bind(('127.0.0.1', 7861)) | |
self.client_listener.listen(1) | |
# Create an HTTP server and bind it to a specific host and port | |
httpd = MyServer(('0.0.0.0', 7860), MyHandler) | |
# Start serving indefinitely | |
httpd.serve_forever() |