File size: 1,862 Bytes
eb73794 0f4704f eb73794 0f4704f eb73794 0f4704f eb73794 0f4704f eb73794 0f4704f eb73794 0f4704f eb73794 0f4704f eb73794 19a4169 0f4704f eb73794 0f4704f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
import subprocess
import sys
import io
import traceback
app = FastAPI()
notebook_globals = {}
@app.get("/", response_class=HTMLResponse)
async def read_root():
with open("index.html", "r", encoding="utf-8") as f:
return f.read()
@app.post("/run_code")
async def run_code(request: Request):
data = await request.json()
code = data.get("code", "")
user_inputs = data.get("inputs", []) # UI se aane wale inputs
input_iterator = iter(user_inputs)
# Custom input function jo UI wale inputs ko use karega
def mock_input(prompt=""):
print(prompt, end="")
try:
val = next(input_iterator)
print(val) # Output mein dikhane ke liye
return val
except StopIteration:
return ""
old_stdout = sys.stdout
redirected_output = sys.stdout = io.StringIO()
# Python ke built-in input ko temporary replace kar rahe hain
import builtins
old_input = builtins.input
builtins.input = mock_input
try:
exec(code, notebook_globals)
output = redirected_output.getvalue()
except Exception as e:
output = redirected_output.getvalue() + "\n--- ERROR ---\n" + traceback.format_exc()
finally:
# Execution ke baad wapas normal kar do
sys.stdout = old_stdout
builtins.input = old_input
return {"output": output}
@app.post("/run_terminal")
async def run_terminal(request: Request):
data = await request.json()
cmd = data.get("cmd", "")
try:
result = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=30)
return {"output": result.stdout + result.stderr}
except Exception as e:
return {"output": f"Command failed: {str(e)}"}
|