File size: 2,014 Bytes
6407b2f
6dea265
5bc4351
382764a
 
 
6407b2f
21fe3fa
 
 
5bc4351
382764a
 
4d30d4b
 
 
 
6dea265
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
382764a
6dea265
 
 
 
 
5bc4351
6dea265
5bc4351
 
6dea265
382764a
6407b2f
6dea265
6407b2f
5bc4351
 
 
6dea265
5bc4351
6dea265
21fe3fa
6dea265
21fe3fa
6dea265
382764a
 
 
 
3b4c467
6dea265
382764a
4d30d4b
6407b2f
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
66
67
68

from flask import Flask, request, jsonify, render_template, stream_with_context, Response
import os
import subprocess
import tempfile
import shutil
import sys

app = Flask(__name__)

# Create a temporary directory for operations
temp_dir = tempfile.mkdtemp()

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

def execute_shell_command(command):
    """Executes a shell command and streams output."""
    process = subprocess.Popen(
        command,
        shell=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True,
        cwd=temp_dir
    )
    for line in iter(process.stdout.readline, ""):
        yield f"{line}<br>"
    for line in iter(process.stderr.readline, ""):
        yield f"Error: {line}<br>"
    process.stdout.close()
    process.stderr.close()
    process.wait()

@app.route("/execute", methods=["POST"])
def execute_code():
    command = request.json.get("code", "").strip()
    if not command:
        return jsonify({"result": "Error: No command provided."})

    try:
        if command.startswith("!"):
            shell_command = command[1:]
            return Response(stream_with_context(execute_shell_command(shell_command)))
        else:
            # Use sys.executable to ensure we're using the correct Python interpreter
            process = subprocess.run(
                [sys.executable, "-c", command],
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                text=True,
                cwd=temp_dir
            )
            return jsonify({"result": process.stdout + process.stderr})
    except Exception as e:
        return jsonify({"result": f"Error: {e}"})

@app.route("/cleanup", methods=["POST"])
def cleanup():
    global temp_dir
    if os.path.exists(temp_dir):
        shutil.rmtree(temp_dir)
    temp_dir = tempfile.mkdtemp()
    return jsonify({"result": "Temporary files cleaned up."})

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=7860, debug=True)