我正在寻找一种在True True循环中引发异常的方法。引发异常的信号起源于线程t_run,该线程连续检查称为pingresponse的全局 bool 变量。当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
最佳答案
从this answer到How 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?看起来很值得。
关于python - 如何在python中的线程循环中引发异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65457487/