【问题标题】:How to raise an exception in a loop out of a thread in python?如何在python线程的循环中引发异常?
【发布时间】:2020-12-26 14:40:34
【问题描述】:

我正在寻找一种在 while True 循环中引发异常的方法。引发异常的信号源自线程 t_run,该线程不断检查名为 pingresponse 的全局布尔变量。一旦 pingresponse 等于“False”,while True 循环应该立即被中断。我不想要的是在 while True 循环中不断检查变量 pingresponse 以检查是否必须引发异常。

到目前为止,我的草稿如下:

import time
import threading
import random

def run():
    # this thread continuously checks the pingresponse
    global pingresponse

    while True:
        # simulating a random pingresponse
        if random.random() > 0.8:
            pingresponse = False
        else:
            pingresponse = True
        time.sleep(0.001)

pingresponse = True
t_run = threading.Thread(target=run)
t_run.start()

while True:
    i = 0
    while True:
        try:
            print('While True loop iteration', i)
            print('pingresponse:' ,pingresponse)
            i += 1

            # "do some work" which includes several consecutive and encapsulated while and for loops
            time.sleep(1) # simulate "do some work" and prevent infinite looping if executed

            # What I want is immediately interrupting the inner while True loop by raising an exception
            # as soon as pingresponse was set to False in the t_run thread
            # The exception should be raised independently of the current position in "do some work"

            # What I don't want is to check the pingresponse variable all the time in "do some work":
            # if not pingresponse:
            #   raise Exception

        except Exception:
            print('pingresponse was set to False in the t_run thread')
            print('start while True loop again with iteration 0')
            break

【问题讨论】:

标签: python multithreading loops exception


【解决方案1】:

使用从this answerHow to exit the entire application from a Python thread?的方法。将您的示例修改为在发生异常时停止一切_thread.interrupt_main() 将在主线程中抛出键盘中断。

import time
import threading
import _thread
import random

def run():
    # this thread continously checks the pingresponse
    global pingresponse

    while True:
        # simulating a random pingresponse
        x = random.random()
        print(f'x:{x:1.3f}')
        if x > 0.98:
            pingresponse = False
        else:
            pingresponse = True
        time.sleep(0.001)
        if not pingresponse:
            _thread.interrupt_main()
            break

pingresponse = True
t_run = threading.Thread(target=run)
t_run.start()

foo = True
while foo:
    i = 0
    while True:
        try:
            print('While True loop iteration', i)
            print('pingresponse:' ,pingresponse)
            i += 1

            # "do some work" which includes several consecutive and encapsulated while and for loops
            time.sleep(1) # simulate "do some work" and prevent infinite looping if executed

        except KeyboardInterrupt as e:
            print('pingresponse was set to False in the t_run thread')
            print('start while True loop again with iteration 0')
            # print(e)
            foo = False
            # raise
            break
    if foo: break

如果使用 _thread.interrupt_main(),您可能需要考虑一些事情——您应该花一些时间研究它。可能希望将signal module 包含在该旅程中。
How do I capture SIGINT in Python? 看起来很值得。

【讨论】:

    猜你喜欢
    • 2019-04-26
    • 2018-09-08
    • 2021-01-16
    • 2023-03-14
    • 2020-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多