Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 621
Nanoni Avatar asked Oct 09 '17 08:10

Nanoni


People also ask

How do you continue a loop even after an exception?

By putting a BEGIN-END block with an exception handler inside of a loop, you can continue executing the loop if some loop iterations raise exceptions. You can still handle an exception for a statement, then continue with the next statement.

How do you continue a loop after catching exception in try catch?

As you are saying that you are using try catch within a for each scope and you wants to continue your loop even any exception will occur. So if you are still using the try catch within the loop scope it will always run that even exception will occur. it is upto you how you deal with exception in your way.

How do you continue a for loop in Python?

The continue statement in Python returns the control to the beginning of the while loop. The continue statement rejects all the remaining statements in the current iteration of the loop and moves the control back to the top of the loop. The continue statement can be used in both while and for loops.


2 Answers

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)
like image 136
bruno desthuilliers Avatar answered Oct 19 '22 07:10

bruno desthuilliers


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)
like image 38
Nanoni Avatar answered Oct 19 '22 06:10

Nanoni