Skip to main content
 首页 » 编程设计

python之等待 url 响应的最长时间

2024年10月25日8insus

我正在为我的代码制作一个简单的更新检查器函数,我将其设置为每次在执行大部分代码之前运行。它通知用户有新版本可供下载。

这是一个 MWE:

import urllib 
 
def updater(__version__): 
    try: 
        # Get latest version number from master repo at Github. 
        f = urllib.urlopen("https://raw.githubusercontent.com/chrisglass" 
            "/django_polymorphic/master/polymorphic/__version__.py") 
        s = f.read().split('"') 
 
        if s[-2] != __version__: 
            print "New version {} is available.".format(s[-2]) 
    except: 
        pass 
 
# Call function to check if new version is available. 
__version__ = '0.1' 
updater(__version__) 

(那个 repo 不是我的,我在这个例子中使用它是因为我使用了它的 __version.py__ 文件的类似版本)

这工作正常,但我担心 Github 最终会花费太长时间来响应,这会阻碍代码的执行。

有没有办法在 5 秒后跳出 try block ?这是解决此问题的推荐方法吗?

请您参考如下方法:

使用urllib2,其urlopen有超时参数。

urllib2.urlopen(url[, data[, timeout[, cafile[, capath[, cadefault[, context]]]]])

https://docs.python.org/2/library/urllib2.html