Skip to main content
 首页 » 编程设计

Python 脚本卡在循环中

2025年05月04日10unruledboy

在我的一个脚本中,我使用以下无限循环来检查事件的互联网连接:

def online_check(): 
    try: 
        con = urllib2.urlopen("http://www.google.com/") 
        data = con.read() 
        logging.debug('{0} Reached the host. Exiting online_check'.format(time.strftime('[ %H:%M:%S ]'))) 
    except: 
        logging.debug('{0} Could not reach host trying again in 3 seconds'.format(time.strftime('[ %H:%M:%S ]'))) 
        time.sleep(3) 
        online_check() 

我知道这不是一个非常优雅的解决方案,但问题是当我启动我的脚本时,它有时会调用 online_check 方法并卡在中间(大约 200 次尝试一次)。脚本仍在运行,没有抛出异常;脚本只是卡住了。我可以按 CTRL+C(即使在脚本被卡住数小时后),它只会抛出异常并继续下一个在线检查。我还重写了脚本以检查“ifconfig”中的 IP 地址,而不是 ping google,不幸的是结果相似。

我做错了什么?我可以重写脚本以防止这种情况发生吗?我可以做些什么来找出这里发生的事情吗?

非常感谢您的帮助。顺便提一句。我使用的是 Python2.7.1,我在 Linux 和 Mac 上都试过这个脚本。

P.S:如果您有关于设计一种在不使用带宽和最小开销的情况下检查连接的方法的建议,我将非常乐意听到。

请您参考如下方法:

您遇到了无限递归,可以采取的一种方法是将参数传递给 online_check 以进行最大检查。

如:

def online_check(max_checks=10, current_check=0): 
    try: 
        con = urllib2.urlopen("http://www.google.com/") 
        data = con.read() 
        logging.debug('{0} Reached the host. Exiting online_check'.format(time.strftime('[ %H:%M:%S ]'))) 
    except: 
        logging.debug('{0} Could not reach host trying again in 3 seconds'.format(time.strftime('[ %H:%M:%S ]'))) 
        if max_checks > current_check: 
          time.sleep(3) 
          online_check(max_checks, current_check+1) 

所以你会这样做:

online_check(5) # for 5 maximum checks 
online_check() # use the default value, which is 10 

我还建议您捕获更具体的异常,以养成更好的编码习惯,但也因为当您执行 CTRL-C 时,Python 会抛出 KeyboardInterrupt 异常,您的代码实际上捕获了该异常,因为您捕获了所有异常。