How to continue for loop after exception in python

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?

asked Oct 9, 2017 at 8:43

4

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]

answered Oct 9, 2017 at 9:22

2

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]

answered Oct 9, 2017 at 9:08

NanoniNanoni

4112 gold badges7 silver badges19 bronze badges

1

Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. [Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.]

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

import random
GREETING = "======> Welcome to Rando 

Chủ Đề