Skip to content

Commit f374382

Browse files
committed
fix(clash): redirect and log Clash output with threads
1 parent 21e8bf5 commit f374382

File tree

1 file changed

+20
-5
lines changed

1 file changed

+20
-5
lines changed

scripts/clash/clash.py

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,13 @@
55
import argparse
66
import logging
77
import requests
8+
import threading
89
import json
910
import urllib.parse
1011

1112
# Assuming speed.py is in the same directory or accessible in PYTHONPATH
1213
from speed import get_top_proxies
14+
import threading
1315

1416
# --- Configuration ---
1517
CLASH_CONTROLLER_HOST = "127.0.0.1"
@@ -151,13 +153,26 @@ def main():
151153
# Step 3: Start Clash in the background
152154
clash_process = None
153155
try:
154-
# It's crucial that Clash starts with the external-controller enabled and accessible
155-
# This is usually configured within the config.yaml itself.
156-
clash_process = subprocess.Popen([clash_executable_path],
157-
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
156+
# Start Clash and redirect its output to a logging function instead of a file
157+
def log_clash_output(pipe, level=logging.INFO):
158+
for line in iter(pipe.readline, b''):
159+
logging.log(level, f"[Clash] {line.decode(errors='replace').rstrip()}")
160+
pipe.close()
161+
162+
clash_process = subprocess.Popen(
163+
[clash_executable_path],
164+
stdout=subprocess.PIPE,
165+
stderr=subprocess.PIPE,
166+
bufsize=1
167+
)
158168
logging.info(f"Clash started with PID {clash_process.pid}")
169+
170+
# Start threads to capture and log stdout and stderr
171+
threading.Thread(target=log_clash_output, args=(clash_process.stdout, logging.INFO), daemon=True).start()
172+
threading.Thread(target=log_clash_output, args=(clash_process.stderr, logging.ERROR), daemon=True).start()
173+
159174
# Give Clash a moment to fully initialize and open its API port
160-
time.sleep(5)
175+
time.sleep(5)
161176
except FileNotFoundError:
162177
logging.critical(f"Clash executable not found at: {clash_executable_path}")
163178
logging.critical("Please ensure the path is correct and Clash is installed.")

0 commit comments

Comments
 (0)