Skip to main content
 首页 » 编程设计

python之为什么这段python代码会在执行过程中挂掉呢

2025年05月04日9dudu

try: 
    html = urlopen('http://glbse.com/api/asset/' + asset.name) 
except: 
    print 'error while updating the price of ' + asset.name 
    continue 
json_txt = html.read() 
ticker = json.loads(json_txt) 
average_price = int(ticker['t24havg']) 
if average_price == 0: 
    average_price = int(ticker['t5davg']) 
if average_price == 0: 
    average_price = int(ticker['t7davg']) 
if average_price == 0: 
    average_price = int(ticker['latest_trade']) 
if average_price == 0: 
    print 'could not determine the price of ' + asset.name 
    continue 
asset.average_price = average_price 

我正在为 urlopen 使用 mechanize。 这段代码(以及程序的其余部分)似乎可以正常运行数小时,但在循环遍历该部分数千次之后,最终会在该部分代码的某处挂起。

它会无限期地挂起。我什至回过头来发现它已经卡在那里好几个小时了。

在谷歌上搜索这个问题,我得到的所有结果都是关于类似问题的报告,其中执行卡在 .read() 上,据报道该问题已在多年前修复。

那么是什么导致执行挂起,我该如何修复或解决它?

请您参考如下方法:

使用 mechanize.Browser().open() 而不是 urlopen 显示“urllib2.URLError urlopen 连接超时”单独使用 urlopen 时不会引发。我强烈怀疑这是问题所在,我的解决方案是在所有情况下都使用 mechanize.Browser().open() 代替 urlopen