python end thread当功能从末端调用并从线程传递异常时
我有以下代码,其中我会定期在背景中运行检查,以便5何时被随机INT发电机击中。
我被卡住的地方正在尝试:
登录时:从random_error登录5时从线程中传递异常,然后可以通过test()函数和test()结束。
当它未达到时:运行Random_Error的线程停止尝试并在test()结束时结束。
from time import sleep
import threading
import random
def random_error():
while True:
sleep(1)
x = random.randint(1,30)
print(x)
if x == 5:
raise ValueError("5 Hit")
def test():
try:
countdown_thread = threading.Thread(target = random_error)
countdown_thread.start()
y = 0
while True:
sleep(1)
print('still going')
y += 1
if y == 10:
print('didnt hit in time')
break
except:
print("Error caught!")
test()
I have the following code where I am running a check periodically in the background for when 5 is hit by a random int generator.
Where I'm getting stuck is trying to:
When it hits: Pass up the exception from the thread running random_error when it hits 5 so then it can be caught by the test() function and test() ends.
When it doesn't hit: The thread running random_error stops trying and ends when test() ends.
from time import sleep
import threading
import random
def random_error():
while True:
sleep(1)
x = random.randint(1,30)
print(x)
if x == 5:
raise ValueError("5 Hit")
def test():
try:
countdown_thread = threading.Thread(target = random_error)
countdown_thread.start()
y = 0
while True:
sleep(1)
print('still going')
y += 1
if y == 10:
print('didnt hit in time')
break
except:
print("Error caught!")
test()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Random_Error
与test
是一个完全不同的线程。无法通过错误。也就是说,您还有很多选择。
测试
可以查看Countdown_thread.is_alive()
。您可以让Random_thread
做一些设置变量或将值放入队列之前的事情,然后才能定期进行test
定期检查。但是,
test
无法获得其他线程的异常。random_error
is a completely different thread fromtest
. There is no way to just pass the error.That said, you still have many options.
test
can look to see ifcountdown_thread.is_alive()
. You can haverandom_thread
do something like set a variable or put a value into a queue before it throws the exception and havetest
check periodically for that.But there is no way that
test
will get the exception thrown by a different thread.