CCCPaste

Computer Emulator

from flask import Flask, request
import webbrowser
import threading
import subprocess
import tempfile
import os
import sys
import io

app = Flask(__name__)

def open_browser():
    webbrowser.open_new_tab("http://127.0.0.1:5000/")

@app.route('/', methods=['GET', 'POST'])
def index():
    code = ""
    output = ""

    if request.method == 'POST':
        code = request.form.get('code', '')
        mode = request.form.get('mode', '')

        if mode == 'python':
            try:
                old_stdout = sys.stdout
                redirected_output = sys.stdout = io.StringIO()
                exec(code, {})
                output = redirected_output.getvalue()
                sys.stdout = old_stdout
            except Exception as e:
                output = f"Python Error: {e}"

        elif mode in ['c', 'cpp', 'c_run']:
            suffix = '.c' if mode in ['c', 'c_run'] else '.cpp'
            compiler = 'gcc' if suffix == '.c' else 'g++'
            with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as src:
                src.write(code.encode('utf-8'))
                src_path = src.name

            exe_path = src_path.replace(suffix, '')
            try:
                subprocess.check_output([compiler, src_path, '-o', exe_path], stderr=subprocess.STDOUT)
                result = subprocess.check_output([exe_path], stderr=subprocess.STDOUT).decode()
                output = result
            except subprocess.CalledProcessError as e:
                output = f"{mode.upper()} Error:\n" + e.output.decode()
            finally:
                os.remove(src_path)
                if os.path.exists(exe_path):
                    os.remove(exe_path)

        elif mode == 'unix':
            cursor_line = int(request.form.get('cursor_line', 0))
            lines = code.split('\n')
            command = lines[cursor_line]
            try:
                result = subprocess.check_output(command, shell=True, stderr=subprocess.STDOUT).decode()
            except subprocess.CalledProcessError as e:
                result = e.output.decode()
            result = result.rstrip()
            lines.insert(cursor_line + 1, result)
            lines.insert(cursor_line + 2, "")
            code = '\n'.join(lines)
            output = ""

    return f"""


    Ubuntu-style Computer Runner
    


    
{output}
""" if __name__ == '__main__': threading.Timer(1, open_browser).start() app.run(debug=True)