python end thread当功能从末端调用并从线程传递异常时

发布于 2025-02-01 07:59:09 字数 833 浏览 3 评论 0原文

我有以下代码,其中我会定期在背景中运行检查,以便5何时被随机INT发电机击中。

我被卡住的地方正在尝试:

  1. 登录时:从random_error登录5时从线程中传递异常,然后可以通过test()函数和test()结束。

  2. 当它未达到时:运行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:

  1. 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.

  2. 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

妳是的陽光 2025-02-08 07:59:09

Random_Errortest是一个完全不同的线程。无法通过错误。

也就是说,您还有很多选择。 测试可以查看Countdown_thread.is_alive()。您可以让Random_thread做一些设置变量或将值放入队列之前的事情,然后才能定期进行test定期检查。

但是,test无法获得其他线程的异常。

random_error is a completely different thread from test. There is no way to just pass the error.

That said, you still have many options. test can look to see if countdown_thread.is_alive(). You can have random_thread do something like set a variable or put a value into a queue before it throws the exception and have test check periodically for that.

But there is no way that test will get the exception thrown by a different thread.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文