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

时间:2018-09-14 07:44:40

标签: python python-3.x assert python-multithreading

请查看此代码:

#! /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)

启动断言时,我需要主循环终止。应该怎么做?

1 个答案:

答案 0 :(得分:0)

感谢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

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