【问题标题】:catch exceptions raised by main in other threads python在其他线程python中捕获main引发的异常
【发布时间】:2023-03-14 17:27:02
【问题描述】:

我试图在不直接引用线程的情况下结束线程执行。因为在整个程序中不可能做到这一点。 作为参考,主程序适用于 Raspberry Pi,我需要它在按下按钮后立即停止执行函数/线程。

我尝试从 main 引发异常,但另一个由于某种原因没有捕获它。

这是我一直在测试的报废程序:

import threading
import time

class Thread_Exception(Exception):
    def __init__(self, msg):
        return super().__init__(msg)


def thread_function(index):
    bool = True
    try:
        while bool:
            print("Print from thread #", index)
            time.sleep(4)
    except Thread_Exception:
        print('Exception thrown, thread #', index)
        bool = False

if __name__ == "__main__":
    try:
        for index in range(3):
            x = threading.Thread(target=thread_function, args=(index,))
            x.start()

        time.sleep(20)
        raise Thread_Exception("intr")

        while True:
            continue

    except KeyboardInterrupt:
        print('Interrupted main')

【问题讨论】:

    标签: python multithreading exception raspberry-pi


    【解决方案1】:

    如何完成的示例:

    import threading 
    import ctypes 
    import time 
    
    class thread_with_exception(threading.Thread): 
        def __init__(self, name): 
            threading.Thread.__init__(self) 
            self.name = name 
    
        def run(self): 
    
            # target function of the thread class 
            try: 
                while True: 
                    print('running ' + self.name) 
            finally: 
                print('ended') 
    
        def get_id(self): 
    
            # returns id of the respective thread 
            if hasattr(self, '_thread_id'): 
                return self._thread_id 
            for id, thread in threading._active.items(): 
                if thread is self: 
                    return id
    
        def raise_exception(self): 
            thread_id = self.get_id() 
            res = ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id, 
                ctypes.py_object(SystemExit)) 
            if res > 1: 
                ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id, 0) 
                print('Exception raise failure') 
    
    t1 = thread_with_exception('Thread 1') 
    t1.start() 
    time.sleep(2) 
    t1.raise_exception() 
    t1.join() 
    

    这篇文章的来源目前可以在这里找到:

    https://www.geeksforgeeks.org/python-different-ways-to-kill-a-thread/

    【讨论】:

    • 仅链接的答案在这里被认为是错误的答案 - 链接可能随时消失,然后分析器完全没用。 cfstackoverflow.com/help/how-to-answer
    • 我已经更新了这篇文章。 @brunodesthuilliers 请查看是否仍需要投反对票
    • 谢谢你让我诚实:-)
    猜你喜欢
    • 2013-09-17
    • 2011-12-05
    • 2021-04-27
    • 1970-01-01
    • 1970-01-01
    • 2015-06-27
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    相关资源
    最近更新 更多