Python3: 在另一个线程上断言时杀死主线程

Python3: Kill main thread when assert on another thread

请看这段代码:

#! /usr/bin/env python3

import threading
import time


def asserter():
    time.sleep(3)
    assert False


threading.Thread(target=asserter).start()

while True:
    print('Main')
    time.sleep(1)

我需要主循环在启动断言时结束。应该怎么做?

您需要在线程本身中捕获任何线程异常。然后您可以将该结果以某种方式传回主线程。这是一个使用共享标志对象指示线程已崩溃的最小示例。然后主循环可以简单地等待该标志改变。

import threading
import time

class Flag:
    ended = False

def asserter(flag):
    time.sleep(3)
    try:
        assert False
    except AssertionError:
        flag.ended = True


thread = threading.Thread(target=asserter, args=(Flag,))
thread.start()

while not Flag.ended:
    print('Main')
    time.sleep(1)
print('done')

感谢 101,我已将代码修改为:

#! /usr/bin/env python3

import threading
import time


class Flag:
    exception = None


def asserter(flag):
    time.sleep(3)
    try:
        assert False
    except Exception as e:
        flag.exception = e


threading.Thread(target=asserter, args=(Flag,)).start()

while not Flag.exception:
    print('Main')
    time.sleep(1)
raise Flag.exception

现在我可以终止主程序,看看发生了什么