【发布时间】: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
【问题讨论】:
-
如果任何链接的问答回答了您的问题,请告诉我们,以便我们将您的问题标记为重复 - 不要接受我的回答(我会删除它)。
-
我不知道您为什么将我的示例修改为“停止一切”,但 _thread.interrupt_main() 函数引发键盘中断是解决我的问题的可能方法。
-
@user111029 我这样做是为了让它在玩的时候停止为我 - 我不希望无限循环挂在那里.
标签: python multithreading loops exception