Online Python Compiler 💻

 pip install flask


app.py

from flask import Flask, render_template, request, jsonify
import subprocess

app = Flask(__name__)

@app.route("/")
def home():
    return render_template("index.html")

@app.route("/run", methods=["POST"])
def run_code():
    code = request.json.get("code", "")

    try:
        # Run the code in a restricted subprocess
        result = subprocess.run(
            ["python", "-c", code],
            capture_output=True,
            text=True,
            timeout=5
        )
        output = result.stdout if result.stdout else result.stderr
    except Exception as e:
        output = str(e)

    return jsonify({"output": output})

if __name__ == "__main__":
    app.run(debug=True)


templates/index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Online Python Compiler</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.12/ace.js"></script>
    <style>
        body { font-family: Arial, sans-serif; text-align: center; }
        #editor { width: 80%; height: 300px; margin: auto; border: 1px solid #ddd; }
        #output { white-space: pre-wrap; background: #f4f4f4; padding: 10px; margin-top: 10px; width: 80%; }
    </style>
</head>
<body>
    <h1>Online Python Compiler 💻</h1>
    <div id="editor">print("Hello, World!")</div>
    <button onclick="runCode()">Run Code</button>
    <pre id="output">Output will appear here...</pre>

    <script>
        var editor = ace.edit("editor");
        editor.setTheme("ace/theme/monokai");
        editor.session.setMode("ace/mode/python");

        function runCode() {
            let code = editor.getValue();
            fetch("/run", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ code: code })
            })
            .then(response => response.json())
            .then(data => document.getElementById("output").innerText = data.output);
        }
    </script>
</body>
</html>


No comments: