gpt4 book ai didi

Python 套接字错误弹性/解决方法

转载 作者:行者123 更新时间:2023-11-28 20:52:00 24 4
gpt4 key购买 nike

我有一个正在运行的脚本正在测试一系列 url 的可用性。

这是功能之一。

def checkUrl(url): # Only downloads headers, returns status code.
p = urlparse(url)
conn = httplib.HTTPConnection(p.netloc)
conn.request('HEAD', p.path)
resp = conn.getresponse()
return resp.status

有时,VPS 会失去连接,当这种情况发生时整个脚本会崩溃。

File "/usr/lib/python2.6/httplib.py", line 914, in request
self._send_request(method, url, body, headers)
File "/usr/lib/python2.6/httplib.py", line 951, in _send_request
self.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
socket.error: [Errno 101] Network is unreachable

我一点也不熟悉在 python 中处理这样的错误。

当网络连接暂时丢失时,防止脚本崩溃的适当方法是什么?


编辑:

我最终得到了这个 - 反馈?

def checkUrl(url): # Only downloads headers, returns status code.
try:
p = urlparse(url)
conn = httplib.HTTPConnection(p.netloc)
conn.request('HEAD', p.path)
resp = conn.getresponse()
return resp.status
except IOError, e:
if e.errno == 101:
print "Network Error"
time.sleep(1)
checkUrl(url)
else:
raise

虽然我不确定我是否完全理解 raise 的作用..

最佳答案

如果你只想处理这个Network is unreachable 101,而让其他异常抛出错误,你可以做如下例子。

from errno import ENETUNREACH

try:
# tricky code goes here

except IOError as e:
# an IOError exception occurred (socket.error is a subclass)
if e.errno == ENETUNREACH:
# now we had the error code 101, network unreachable
do_some_recovery
else:
# other exceptions we reraise again
raise

关于Python 套接字错误弹性/解决方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7950759/

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