【问题标题】:Why would this section of python code hang during execution?为什么这部分python代码会在执行过程中挂起?
【发布时间】: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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2017-03-26
    • 2012-01-16
    • 1970-01-01
    • 1970-01-01
    • 2013-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多