diff --git a/CF-Handler.py b/CF-Handler.py index 7d89d5e..d3b821b 100644 --- a/CF-Handler.py +++ b/CF-Handler.py @@ -1,20 +1,74 @@ import subprocess import time +import threading +import sys + +def autostats(process): + while process.poll() is None: + try: + process.stdin.write(b"/stats\n") + process.stdin.flush() + except: + break + time.sleep(3600) + +def user_input(process): + """Handles user input and sends it to the process""" + while process.poll() is None: + try: + user_input = input("> ") + if user_input: + process.stdin.write(f"{user_input}\n".encode()) + process.stdin.flush() + except EOFError: + break + except Exception as e: + print(f"Input error: {e}") def run_and_monitor(): try: - # Start the child process print("Starting catflipper-linux...") - process = subprocess.Popen(["./catflipper-linux"]) - process.wait() + process = subprocess.Popen( + ["./catflipper-linux"], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + universal_newlines=False + ) + stats_thread = threading.Thread( + target=autostats, + args=(process,), + daemon=True + ) + stats_thread.start() + input_thread = threading.Thread( + target=user_input, + args=(process,), + daemon=True + ) + input_thread.start() + def output(): + while process.poll() is None: + line = process.stdout.readline() + if line: + sys.stdout.buffer.write(line) + sys.stdout.buffer.flush() - print("catflipper-linux crashed. Restarting...") + output_thread = threading.Thread( + target=output, + daemon=True + ) + output_thread.start() + process.wait() + print("\ncatflipper-linux crashed. Restarting...") time.sleep(2) run_and_monitor() except KeyboardInterrupt: - print("Process monitor interrupted by user.") - process.terminate() # ensure process cleanup on exit + print("\nProcess monitor interrupted by user.") + if process: + process.terminate() + except Exception as e: print(f"Error occurred: {e}") time.sleep(2)