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)