我正在寻找一种在True 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
从这个答案到使用方法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(),可能需要考虑一些事情-您应该花一些时间进行研究。可能希望在该过程中包括信号模块。
如何在Python中捕获SIGINT?看起来值得。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句