我有这个脚本在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
我在这里缺少什么?在互联网上搜索没有多大帮助: - (
答案 0 :(得分: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
,因为这个库可能会有所改进。
答案 1 :(得分:0)
问题实际上是已设置为无法访问的服务器的http_proxy环境变量。我用
绕过了它urllib.urlopen(stats_URI, proxies={}).read()
从那时起,一切都运转良好。
非常感谢,
S上。