from flask import Flask, render_template_string, jsonify from apscheduler.schedulers.background import BackgroundScheduler import subprocess import threading from datetime import datetime app = Flask(__name__) execution_logs = [] MAX_LOG_ENTRIES = 1000 def run_cli_script(): """Runs cli.py and streams logs in real-time to both UI and terminal.""" global execution_logs # Declare the global variable timestamp = datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S UTC") try: process = subprocess.Popen( ["python3", "cli.py"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, # Merge stdout and stderr text=True, bufsize=1 ) for line in process.stdout: execution_logs.append({'time': timestamp, 'output': line.strip(), 'error': ''}) print(line, end="") # Trim logs efficiently if len(execution_logs) > MAX_LOG_ENTRIES: execution_logs = execution_logs[-MAX_LOG_ENTRIES:] except Exception as e: execution_logs.append({'time': timestamp, 'output': '', 'error': str(e)}) print(f"Error: {str(e)}") def start_initial_run(): threading.Thread(target=run_cli_script, daemon=True).start() scheduler = BackgroundScheduler(daemon=True) scheduler.add_job( run_cli_script, 'interval', hours=3, id='main_job', next_run_time=datetime.now() ) scheduler.start() start_initial_run() @app.route('/') def home(): """Main UI displaying logs and next run time.""" job = scheduler.get_job('main_job') next_run = job.next_run_time.strftime('%Y-%m-%d %H:%M:%S UTC') if job else 'N/A' return render_template_string('''
Next run: {{ next_run }}