异常后如何继续循环?

Nan*_*oni 5 python loops exception-handling

我有一个代码,其中im遍历主机列表并将连接追加到连接列表,如果出现连接错误,我想跳过该错误并继续使用主机列表中的下一个主机。

这是我现在拥有的:

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)
Run Code Online (Sandbox Code Playgroud)

这无法正常工作,如果连接失败,它将一次又一次地循环同一主机,直到建立连接为止,我该如何解决?

bru*_*ers 12

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

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)
Run Code Online (Sandbox Code Playgroud)

  • 考虑到“else”并且在 try 块之后没有附加代码,“continue”不是多余的吗? (3认同)