线程未结束/timeou

2024-06-13 11:33:02 发布

您现在位置:Python中文网/ 问答频道 /正文

总的来说,我试着解决一个简单的问题。 我尝试访问一个网站,如果一个错误(例外)发生后,应该给予另一个延迟期后尝试。如果这可能是一个问题,那么整个代码都嵌入到一个无限循环中。我的第一次尝试是这样的:

while 1 == 1
  connected = False
    while not connected:
        try:
            br.follow_link(l)
            connected = True
        except:
            time.sleep(61)

但每次发生异常时时间。睡眠(61)永无止境。 我阅读了一些关于线程的内容,并实现了以下内容:

def sleeper(sec):
    time.sleep(sec)

while 1 == 1
  connected = False
    while not connected:
        try:
            br.follow_link(l)
            connected = True
        except:
            t = Thread(target=sleeper, args=(61,))
            t.start()
            t.join(62)

所以基本上是相同的概念,但这次t.join(62)从未终止,即使超时62秒。所以我在这里有点迷茫,因为a不能解决我的简单问题。你有什么想法吗?你知道吗


Tags: brfalsetruetimelinknotsleepsec
1条回答
网友
1楼 · 发布于 2024-06-13 11:33:02

所以,我编写了一个小的测试python脚本,一切正常:

import threading
import time

class MyException(Exception):
    pass


def sleeper(sec):
    print "In thread"
    time.sleep(sec)

def follow_link():
    raise MyException("My Error")


while True:
    connected = False
    while not connected:
        try:
            follow_link()
            connected = True
        except Exception, e:
            print e
            t = threading.Thread(target=sleeper, args=(5,))
            t.start()
            t.join(7)

但我认为这实际上和您的第一个示例代码做了相同的事情,因为(正如我在调试器中看到的)t.join也冻结了执行。你知道吗

相关问题 更多 >