You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python线程while循环停止及日志不输出问题求助

Hey there! Let's tackle your two issues one by one—missing logs from your TransmitThread and old threads stopping unexpectedly when stored in a dictionary. Based on your code structure, here’s what I suggest:

Issue 1: No Logs Showing Up from TransmitThread

The most likely culprits here are unbuffered print statements or misaligned logging configurations with Flask. Here’s how to fix it:

  • Replace print() with Python’s logging module: Print statements in background threads often get buffered or ignored by Flask’s default logging setup. Swap your print() calls with logging.info(), logging.debug(), or logging.error() to integrate with Flask’s logging system. For example:
    import logging
    
    class TransmitThread(threading.Thread):
        def run(self):
            logging.info("Transmit thread started successfully")
            # ... your transmission logic ...
            logging.debug("Sending data to USRP device")
    
  • Configure Flask’s logging level: Make sure Flask’s logger is set to capture the level of logs you’re generating. Add this when initializing your app:
    from flask import Flask
    import logging
    
    app = Flask(__name__)
    # Set to DEBUG to capture all log levels, adjust as needed
    app.logger.setLevel(logging.DEBUG)
    # Optional: Add a formatter for clearer logs
    logging.basicConfig(format='%(asctime)s - %(threadName)s - %(levelname)s - %(message)s')
    
  • Force flush if sticking with print(): If you prefer to keep using print(), add flush=True to every call to bypass output buffering:
    print("Transmission in progress", flush=True)
    
Issue 2: Old Threads Stopping Unexpectedly

Threads stopping without being explicitly told usually stems from uncaught exceptions, thread-safety issues with your stop flag, or Flask’s process/thread isolation. Let’s break down fixes:

  1. Catch exceptions in the thread’s run() method: If an error occurs (e.g., USRP device disconnects, IO failure), the thread will crash silently without logging. Wrap your transmission logic in a try-except block to capture and log errors:

    class TransmitThread(threading.Thread):
        def run(self):
            try:
                while not self.stop_event.is_set():
                    # ... your transmission logic ...
            except Exception as e:
                # Log the full error traceback for debugging
                logging.error(f"Thread crashed unexpectedly: {str(e)}", exc_info=True)
            finally:
                logging.info("Thread exited gracefully")
    
  2. Use a thread-safe stop flag instead of a boolean: Your thdRunning boolean isn’t thread-safe—race conditions can cause the thread to miss the stop signal. Replace it with threading.Event(), which is designed for cross-thread communication:

    import threading
    
    class TransmitThread(threading.Thread):
        def __init__(self):
            super().__init__()
            self.stop_event = threading.Event()  # Thread-safe flag
    
        def run(self):
            logging.info("Thread started")
            while not self.stop_event.is_set():
                # ... keep transmitting ...
            logging.info("Thread stopped")
    
        def stop(self):
            self.stop_event.set()  # Safely signal the thread to stop
    
  3. Fix Flask’s thread/process isolation for your thread dictionary: If you’re running Flask with threaded=True or multiple processes, the dictionary storing your threads might not be shared across all requests.

    • For single-threaded/single-process development (default app.run()), ensure your dictionary is a global variable initialized once outside request handlers.
    • For multi-process setups, use a shared dictionary from multiprocessing.Manager() to ensure all processes access the same thread references:
      from multiprocessing import Manager
      
      # Initialize shared dictionary once before starting the app
      thread_store = Manager().dict()
      
      @app.route('/start-thread', methods=['POST'])
      def start_thread():
          new_thread = TransmitThread()
          thread_store["active_thread"] = new_thread
          new_thread.start()
          return {"status": "started"}
      
  4. Verify thread references aren’t being garbage collected: Ensure your dictionary isn’t being reinitialized or cleared accidentally. Keep it as a top-level variable in your Flask app file, not inside a request handler or function that gets re-run.

Start with fixing the logging first—once you can see what’s happening inside the thread, debugging why it stops will be much easier!

内容的提问来源于stack exchange,提问作者Sagar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:56:43