如何在异常后继续循环?

时间:2017-10-09 08:43:18

标签: python loops exception-handling

我有一个代码,其中我循环遍历主机列表并将连接附加到连接列表,如果有连接错误,我想跳过它并继续主机列表中的下一个主机。

这是我现在所拥有的:

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)

这不能正常工作,如果连接失败,它会一次又一次地循环同一个主机,直到它建立连接,我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

你自己的答案在很多方面仍然是错误的......

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)

答案 1 :(得分:0)

好吧,让它工作,我需要添加继续,马克和前面提到的如果检查内部最终总是返回true,所以这是固定的。

这是固定代码,它不会添加失败的连接,并在此之后正常继续循环:

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)