gpt4 book ai didi

python - 处理 urllib2 返回的 badstatusline(line)?

转载 作者:太空狗 更新时间:2023-10-30 00:45:33 26 4
gpt4 key购买 nike

我有一个简单的互联网检查器正在运行,但它偶尔会返回一个我似乎无法处理的错误...

函数如下:

def internet_on():

try:
urllib2.urlopen("http://google.co.uk/", timeout = 10)
return True
except urllib2.URLError as e:
return False
except socket.timeout as e:
return False

这是错误:

Traceback (most recent call last):
File "C:/Testscript.py", line 117, in internet_on
urllib2.urlopen("http://google.co.uk/", timeout = 10)
File "C:\Python27\lib\urllib2.py", line 127, in urlopen
return _opener.open(url, data, timeout)
File "C:\Python27\lib\urllib2.py", line 410, in open
response = meth(req, response)
File "C:\Python27\lib\urllib2.py", line 523, in http_response
'http', request, response, code, msg, hdrs)
File "C:\Python27\lib\urllib2.py", line 442, in error
result = self._call_chain(*args)
File "C:\Python27\lib\urllib2.py", line 382, in _call_chain
result = func(*args)
File "C:\Python27\lib\urllib2.py", line 629, in http_error_302
return self.parent.open(new, timeout=req.timeout)
File "C:\Python27\lib\urllib2.py", line 404, in open
response = self._open(req, data)
File "C:\Python27\lib\urllib2.py", line 422, in _open
'_open', req)
File "C:\Python27\lib\urllib2.py", line 382, in _call_chain
result = func(*args)
File "C:\Python27\lib\urllib2.py", line 1214, in http_open
return self.do_open(httplib.HTTPConnection, req)
File "C:\Python27\lib\urllib2.py", line 1187, in do_open
r = h.getresponse(buffering=True)
File "C:\Python27\lib\httplib.py", line 1045, in getresponse
response.begin()
File "C:\Python27\lib\httplib.py", line 409, in begin
version, status, reason = self._read_status()
File "C:\Python27\lib\httplib.py", line 373, in _read_status
raise BadStatusLine(line)
BadStatusLine: ''

如何处理此错误以返回 false,我希望 internet_on 函数在连接时返回 true,但如果不是 true,则应返回 false..

最佳答案

import httplib

...


def internet_on():
try:
urllib2.urlopen("http://google.co.uk/", timeout = 10)
return True
except (IOError, httplib.HTTPException):
return False

关于python - 处理 urllib2 返回的 badstatusline(line)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17253955/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com