1

我有这个在 Python 2.7 中运行良好但在 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

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

4

2 回答 2

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,因为这个库可能是一个改进。

于 2012-08-30T13:56:05.823 回答
0

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

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

从那时起一切都很好。

非常感谢,

S。

于 2012-08-31T14:20:27.373 回答