from flask import Flask, request, redirect, url_for
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():
search_query = request.args.get('search')
if search_query:
url = f"https://www.google.com/search?q={search_query}"
threading.Thread(target=lambda: webbrowser.open_new_tab(url)).start()
return redirect(url_for('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)
return f'''
Offline Code Runner
'''
if __name__ == '__main__':
threading.Timer(1, open_browser).start()
app.run(debug=True)