[英]how to continue for loop after exception?
我有一個代碼,其中我循環通過主機列表並附加到連接列表的連接,如果有連接錯誤,我想跳過它並繼續主機列表中的下一個主機。
繼承人我現在擁有的:
def do_connect(self):
"""Connect to all hosts in the hosts list"""
for host in self.hosts:
try:
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(host['ip'], port=int(host['port']), username=host['user'], timeout=2)
except:
pass
#client.connect(host['ip'], port=int(host['port']), username=host['user'], password=host['passwd'])
finally:
if paramiko.SSHException():
pass
else:
self.connections.append(client)
這不能正常工作,如果連接失敗,它只會一次又一次地循環同一個主機,直到它建立連接,我該如何解決這個問題?
你自己的答案在很多方面仍然是錯誤的......
import logging
logger = logging.getLogger(__name__)
def do_connect(self):
"""Connect to all hosts in the hosts list"""
for host in self.hosts:
# this one has to go outside the try/except block
# else `client` might not be defined.
client = paramiko.SSHClient()
try:
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(host['ip'], port=int(host['port']), username=host['user'], timeout=2)
# you only want to catch specific exceptions here
except paramiko.SSHException as e:
# this will log the full error message and traceback
logger.exception("failed to connect to %(ip)s:%(port)s (user %(user)s)", host)
continue
# here you want a `else` clause not a `finally`
# (`finally` is _always_ executed)
else:
self.connections.append(client)
好吧,讓它工作,我需要添加繼續,馬克和前面提到的如果檢查里面最終總是返回真,所以這是固定的。
這是固定代碼,它不會添加失敗的連接,並在此之后正常繼續循環:
def do_connect(self):
"""Connect to all hosts in the hosts list"""
for host in self.hosts:
try:
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(host['ip'], port=int(host['port']), username=host['user'], timeout=2)
except:
continue
#client.connect(host['ip'], port=int(host['port']), username=host['user'], password=host['passwd'])
finally:
if client._agent is None:
pass
else:
self.connections.append(client)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.