【发布时间】:2012-06-13 19:07:14
【问题描述】:
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
我正在使用 mechanize 进行 urlopen。 这段代码(和程序的其余部分)似乎可以运行好几个小时,但是在循环了这部分数千次之后,最终会挂在这部分代码的某个地方。
它会无限期挂起。我什至回过头来发现它已经挂了好几个小时了。
我在谷歌上搜索的所有问题都是关于类似问题的报告,其中执行挂起在 .read() 上,据报道该问题已在几年前修复。
那么是什么导致执行挂起,我该如何修复或解决它?
【问题讨论】:
-
我看到
json.loads在没有给出有效的 json 文件时挂起。你确定你总是传递一个正确的 json 文件吗? -
除了
except:之外不要使用裸词;它会捕获 any 异常。只捕捉你需要捕捉的东西。添加一些日志记录;这应该可以帮助您发现问题所在。 -
您可以尝试将可选的超时参数传递给 urllib2.urlopen 看看是否有帮助。
-
@MRAB -- 包括一个 KeyboardInterrupt(很容易发送,并且回溯会告诉你代码挂在哪里的确切位置)。
-
@MRAB 问题是,据我所知,它没有发现任何异常,因为如果有异常,它会转到下一个资产,而这个问题不会出现。
标签: python python-2.7 mechanize urllib2