2012-08-30 72 views
1

我有这样的脚本,在Python 2.7运行良好,但不是在2.6:解析JSON从Python中的URL 2.6

def main(): 
    tempfile = '/tmp/tempfile' 
    stats_URI="http://x.x.x.x/stats.json" 
    hits_ = 0 
    advances_ = 0 
    requests = 0 
    failed = 0 

    as_data = urllib.urlopen(stats_URI).read() 
    data = json.loads(as_data) 

    for x, y in data['hits-seen'].iteritems(): 
     hits_ += y 

    # Total of failed vtop requests 
    for x, y in data['vals-failed'].iteritems(): 
     failed += y 

    requests = data['requests'] 

    advances_ = requests - failed 

    f = open(tempfile,'w') 

    line1 = "hits: " + str(hits_) + "\n" 
    line2 = "advances: " + str(advances_) + "\n" 

    f.write(line1) 
    f.write(line2) 
    f.close() 

    return 0 

,我得到的错误消息称:

Traceback (most recent call last): File "./json.test.py", line 14, in <module> 
    main() File "./json.test.py", line 8, in main 
    as_data = urllib.urlopen(stats_URI).read() File "/usr/lib/python2.6/urllib.py", line 86, in urlopen 
    return opener.open(url) File "/usr/lib/python2.6/urllib.py", line 207, in open 
    return getattr(self, name)(url) File "/usr/lib/python2.6/urllib.py", line 346, in open_http 
    h.endheaders() File "/usr/lib/python2.6/httplib.py", line 908, in endheaders 
    self._send_output() File "/usr/lib/python2.6/httplib.py", line 780, in _send_output 
    self.send(msg) File "/usr/lib/python2.6/httplib.py", line 739, in send 
    self.connect() File "/usr/lib/python2.6/httplib.py", line 720, in connect 
    self.timeout) File "/usr/lib/python2.6/socket.py", line 561, in create_connection 
    raise error, msg IOError: [Errno socket error] [Errno 110] Connection timed out 

什么我在这里想念吗?在互联网上搜索没有帮助太多:-(

+3

这有什么好做JSON;该脚本由于连接超时而失败。很可能它与python 2.6无关.. –

+1

仅在Python 2.6上发生“连接超时”错误吗? – jfs

回答

0

问题实际上是http_proxy e已设置为无法访问的服务器的环境变量。我绕过它通过使用

urllib.urlopen(stats_URI, proxies={}).read() 

一切工作正常从那时起。

非常感谢,

S.

0

如何尝试几次连接:

as_data = get_urldata(stats_URI) #Note this will be None, if it failed to connect after 20 attempts 

其中

def get_urldata(url, t=20): 
    '''attempt to read the url t times (by default 20)''' 
    for i in xrange(t): 
     try: 
      return urllib.urlopen(url).read() 
     except IOError: 
      pass 

也许你应该使用urllib2而非urllib,因为这库可能是一种改进