File size: 2,039 Bytes
2c91ea0
5bc4351
2c91ea0
382764a
 
21fe3fa
 
2c91ea0
 
 
 
 
 
 
 
 
21fe3fa
382764a
1917e67
4d30d4b
2c91ea0
1917e67
 
2c91ea0
1917e67
 
2c91ea0
 
 
4d30d4b
2c91ea0
 
 
 
a794cee
2c91ea0
 
 
 
 
 
 
 
 
 
 
a794cee
2c91ea0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
382764a
5bc4351
2c91ea0
 
 
 
21fe3fa
382764a
2c91ea0
1917e67
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
69
70
71
72
73
74
75
76
77
78
79
from flask import Flask, request, jsonify, render_template
import os
import subprocess
import tempfile
import shutil

app = Flask(__name__)
BASE_DIR = tempfile.mkdtemp()  # Temporary directory for executing user scripts


def cleanup_temp_dir():
    """Cleans up the temporary directory."""
    try:
        shutil.rmtree(BASE_DIR)
    except Exception as e:
        print(f"Error cleaning up temp dir: {e}")


@app.route('/')
def index():
    """Render the main terminal interface."""
    return render_template('index.html')


@app.route('/run', methods=['POST'])
def run_command():
    """Executes Python scripts or commands."""
    user_input = request.json.get('code', '')
    response = {"output": "", "error": ""}

    # Save the user's Python script to a temporary file
    temp_file_path = os.path.join(BASE_DIR, "user_script.py")
    with open(temp_file_path, 'w') as script_file:
        script_file.write(user_input)

    # Execute the script and capture output
    try:
        process = subprocess.Popen(
            ["python3", temp_file_path],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True
        )
        stdout, stderr = process.communicate()
        response["output"] = stdout
        response["error"] = stderr
    except Exception as e:
        response["error"] = str(e)

    # Cleanup temporary file
    if os.path.exists(temp_file_path):
        os.remove(temp_file_path)

    return jsonify(response)


@app.route('/clean', methods=['POST'])
def clean():
    """Cleans the temporary directory when the user leaves."""
    cleanup_temp_dir()
    return jsonify({"status": "Temporary files cleaned."})


@app.before_first_request
def setup():
    """Set up the temporary directory before the first request."""
    if not os.path.exists(BASE_DIR):
        os.makedirs(BASE_DIR)


@app.teardown_appcontext
def teardown(exception):
    """Clean up after the app shuts down."""
    cleanup_temp_dir()


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