简体   繁体   English

如何在异常后继续循环?

[英]how to continue for loop after exception?

I have a code where im looping through hosts list and appending connections to connections list, if there is a connection error, i want to skip that and continue with the next host in the hosts list. 我有一个代码,其中我循环通过主机列表并附加到连接列表的连接,如果有连接错误,我想跳过它并继续主机列表中的下一个主机。

Heres what i have now: 继承人我现在拥有的:

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)

This does not work properly, if connection fails it just loops the same host again and again forever, till it establishes connection, how do i fix this? 这不能正常工作,如果连接失败,它只会一次又一次地循环同一个主机,直到它建立连接,我该如何解决这个问题?

Your own answer is still wrong on quite a few points... 你自己的答案在很多方面仍然是错误的......

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)

Ok, got it working, i needed to add the Continue, mentioned by Mark and also the previous if check inside finally was always returning true so that was fixed aswell. 好吧,让它工作,我需要添加继续,马克和前面提到的如果检查里面最终总是返回真,所以这是固定的。

Here is the fixed code, that doesnt add failed connections and continues the loop normally after that: 这是固定代码,它不会添加失败的连接,并在此之后正常继续循环:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM