Hướng dẫn how do you continue a loop after catching exception in try catch python? - làm thế nào để bạn tiếp tục một vòng lặp sau khi bắt ngoại lệ trong try catch python?

Tôi có một mã trong đó tôi lặp qua danh sách máy chủ và nối các kết nối vào danh sách kết nối, nếu có lỗi kết nối, tôi muốn bỏ qua điều đó và tiếp tục với máy chủ tiếp theo trong danh sách máy chủ.

Đây là những gì tôi có bây giờ:

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]

Điều này không hoạt động đúng, nếu kết nối không thành công, nó chỉ lặp lại cùng một máy chủ mãi mãi, cho đến khi nó thiết lập kết nối, làm thế nào để tôi khắc phục điều này?

Đã hỏi ngày 9 tháng 10 năm 2017 lúc 8:43Oct 9, 2017 at 8:43

4

Câu trả lời của riêng bạn vẫn còn sai ở một vài điểm ...

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]

Đã trả lời ngày 9 tháng 10 năm 2017 lúc 9:22Oct 9, 2017 at 9:22

2

OK, nó đã hoạt động, tôi cần thêm sự tiếp tục, được đề cập bởi Mark và cũng là trước đây nếu kiểm tra bên trong cuối cùng luôn luôn trả về đúng để điều đó đã được cố định.

Đây là mã cố định, không thêm kết nối thất bại và tiếp tục vòng lặp bình thường sau đó:

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]

Đã trả lời ngày 9 tháng 10 năm 2017 lúc 9:08Oct 9, 2017 at 9:08

NanoninanoniNanoni

4112 Huy hiệu vàng7 Huy hiệu bạc19 Huy hiệu đồng2 gold badges7 silver badges19 bronze badges

1

Bây giờ vòng lặp bỏ qua chức năng in cuối cùng:continue statement is one of the loop statements that control the flow of the loop. More specifically, the continue statement skips the “rest of the loop” and jumps into the beginning of the next iteration.

Điều này rất hữu ích nếu chức năng in cuối cùng là thứ bạn không nên vô tình chạy khi xảy ra lỗi.break statement, the continue does not exit the loop.

Sự kết luậncontinue to skip printing the even numbers:

n = 0
while n < 10:
    n += 1
    if n % 2 == 0:
        continue
    print[n]

Hôm nay bạn đã học được cách sử dụng tuyên bố tiếp tục trong Python.print function when it encounters an even number [a number divisible by 2]:

1
3
5
7
9

Tóm lại, tuyên bố tiếp tục trong Python bỏ qua phần còn lại của vòng lặp và bắt đầu một lần lặp. Điều này rất hữu ích nếu phần còn lại của vòng lặp bao gồm mã không cần thiết.n is even:

Ví dụ: bạn có thể bỏ qua các số in thậm chí in và chỉ in các số lẻ bằng cách:

Ở đây, vòng lặp bỏ qua chức năng in cuối cùng nếu nó gặp một số chẵn.continue statement jumps out of the current iteration of a loop to start the next iteration.

Tuy nhiên, một câu lệnh IF-Else thường tốt hơn so với việc sử dụng câu lệnh IF có câu lệnh tiếp tục. Tuy nhiên, với nhiều điều kiện, câu lệnh tiếp tục ngăn chặn các khối if-else lồng nhau không khả thi để quản lý.continue statement is to check if a condition is met, and skip the rest of the loop based on that.

Cảm ơn vì đã đọc. Tôi hy vọng bạn thích nó.continue statement may sometimes be a key part to make an algorithm work. Sometimes it just saves resources because it prevents running excess code.

Mã hóa hạnh phúc!continue statement can be used with both for and while loops.

while condition:
    if other_condition:
        continue

for elem in iterable:
    if condition:
        continue

Chẳng hạn, bạn có thể sử dụng câu lệnh tiếp tục để bỏ qua các số in thậm chí:continue statement to skip printing even numbers:

n = 0
while n < 10:
    n += 1
    if n % 2 == 0:
        continue
    print[n]

Output:

1
3
5
7
9

Tiếp tục VS IF-Else trong Python

Câu lệnh tiếp tục hoạt động theo cách tương tự như một câu lệnh if-else. Sử dụng câu lệnh tiếp tục về cơ bản giống như đặt mã vào một khối if-outs.continue statement behaves in the same way as an if-else statement. Using the continue statement is essentially the same as putting the code into an if-else block.

Trong các trường hợp đơn giản, nó thường là một ý tưởng tốt hơn để sử dụng một câu lệnh if-else, thay vì tiếp tục!continue!

Chẳng hạn, hãy để vòng lặp qua các số từ 1 đến 10 và in loại kỳ lạ của các số:

Đây là cách tiếp tục tiếp tục:continue approach:

for num in range[1, 10]:
    if num % 2 == 0:
        print["Even number: ", num]
        continue
    print["Odd number: ", num]

Output:

Odd number:  1
Even number:  2
Odd number:  3
Even number:  4
Odd number:  5
Even number:  6
Odd number:  7
Even number:  8
Odd number:  9

Sau đó, hãy để Lừa chuyển đổi phương pháp này thành một tuyên bố IF-Else:

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]
0

Output:

Odd number:  1
Even number:  2
Odd number:  3
Even number:  4
Odd number:  5
Even number:  6
Odd number:  7
Even number:  8
Odd number:  9

Như bạn có thể thấy, cách tiếp cận thứ hai cung cấp một cách sạch hơn để thể hiện ý định của bạn. Bằng cách nhìn vào đoạn mã này, nó ngay lập tức rõ ràng những gì nó làm. Tuy nhiên, nếu bạn nhìn vào cách tiếp cận trước đây với các tuyên bố tiếp tục, bạn cần phải gãi đầu một chút trước khi bạn thấy những gì đang diễn ra.continue statements, you need to scratch your head a bit before you see what is going on.

Đây là một ví dụ tuyệt vời về khi bạn có thể sử dụng câu lệnh if-else thay vì sử dụng câu lệnh tiếp tục.continue statement.

Ngoài ra, nếu bạn xem xét ví dụ trước đó về việc in các số lẻ từ một phạm vi:

n = 0
while n < 10:
    n += 1
    if n % 2 == 0:
        continue
    print[n]

Bạn thấy nó là sạch hơn khi sử dụng một trong khi kiểm tra ở đây, thay vì trộn nó với câu lệnh tiếp tục:continue statement:

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]
3

Nhưng bây giờ bạn có thể tự hỏi tại sao bạn nên sử dụng tiếp tục nếu nó chỉ làm cho mã không thể đọc được hơn. Hãy cùng xem một số trường hợp sử dụng tốt cho tuyên bố tiếp tục.continue if it only makes code more unreadable. Let’s see some good use cases for the continue statement.

Khi sử dụng tiếp tục Python

Như đã nêu trước đó, bạn có thể thay thế câu lệnh tiếp tục bằng các câu lệnh if-else.continue statement with if-else statements.

Ví dụ: đoạn mã này:

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]
4

Có giống như cái này không:

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]
5

Trong các trường hợp đơn giản, sử dụng IF-Else qua tiếp tục là một ý kiến ​​hay. Nhưng chắc chắn có một số trường hợp sử dụng cho tuyên bố tiếp tục quá.continue is a good idea. But there are definitely some use cases for the continue statement too.

Ví dụ:

  1. Bạn có thể tránh các câu lệnh if-else sử dụng tiếp tục.continue.
  2. Tiếp tục có thể giúp bạn với ngoại lệ trong một vòng lặp. can help you with exceptionhandling in a for loop.

Hãy cùng xem các ví dụ về cả hai.

1. Tránh các câu lệnh if-else trong vòng lặp tiếp tục trong Python

Hãy tưởng tượng bạn có nhiều điều kiện mà bạn muốn bỏ qua vòng lặp. Nếu bạn chỉ dựa vào các câu lệnh IF-Else, mã của bạn sẽ trở thành sự hỗn loạn hình kim tự tháp:

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]
6

Đây là mọi cơn ác mộng của nhà phát triển. Một mớ hỗn độn if-else là không khả thi để quản lý.

Tuy nhiên, bạn có thể làm cho mã sạch hơn và tâng bốc bằng cách sử dụng câu lệnh tiếp tục:continue statement:

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]
7

Bây giờ, thay vì có một cấu trúc lồng nhau của các câu lệnh if-hữu ích, bạn chỉ có cấu trúc phẳng của các câu lệnh IF. Điều này có nghĩa là mã dễ hiểu hơn và dễ dàng hơn để duy trì các vấn đề về tuyên bố tiếp tục.continue statement.

2. Tiếp tục xử lý lỗi - Hãy thử, ngoại trừ, tiếp tục

Nếu bạn cần xử lý các ngoại lệ trong một vòng lặp, hãy sử dụng câu lệnh tiếp tục để bỏ qua phần còn lại của vòng lặp.continue statement to skip the “rest of the loop”.

Ví dụ: hãy xem đoạn mã này xử lý lỗi trong một vòng lặp:

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]
8

Bây giờ, vòng lặp thực thi chức năng in cuối cùng bất kể ngoại lệ có bị ném hay không:print function regardless of whether an exception is thrown or not:

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]
9

Để tránh điều này, hãy sử dụng câu lệnh tiếp tục trong khối ngoại trừ. Điều này bỏ qua phần còn lại của vòng lặp khi một ngoại lệ xảy ra.continue statement in the except block. This skips the rest of the loop when an exception occurs.

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]
0

Bây giờ vòng lặp bỏ qua chức năng in cuối cùng:print function:

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]
1

Điều này rất hữu ích nếu chức năng in cuối cùng là thứ bạn không nên vô tình chạy khi xảy ra lỗi.print function was something you should not accidentally run when an error occurs.

Sự kết luận

Hôm nay bạn đã học được cách sử dụng tuyên bố tiếp tục trong Python.continue statement in Python.

Tóm lại, tuyên bố tiếp tục trong Python bỏ qua phần còn lại của vòng lặp và bắt đầu một lần lặp. Điều này rất hữu ích nếu phần còn lại của vòng lặp bao gồm mã không cần thiết.continue statement in Python skips “the rest of the loop” and starts an iteration. This is useful if the rest of the loop consists of unnecessary code.

Ví dụ: bạn có thể bỏ qua các số in thậm chí in và chỉ in các số lẻ bằng cách:

n = 0
while n < 10:
    n += 1
    if n % 2 == 0:
        continue
    print[n]

Ở đây, vòng lặp bỏ qua chức năng in cuối cùng nếu nó gặp một số chẵn.print function if it encounters an even number.

Tuy nhiên, một câu lệnh IF-Else thường tốt hơn so với việc sử dụng câu lệnh IF có câu lệnh tiếp tục. Tuy nhiên, với nhiều điều kiện, câu lệnh tiếp tục ngăn chặn các khối if-else lồng nhau không khả thi để quản lý.continue statement. However, with multiple conditions, the continue statement prevents nested if-else blocks that are infeasible to manage.

Cảm ơn vì đã đọc. Tôi hy vọng bạn thích nó.

Mã hóa hạnh phúc!

Đọc thêm

50 câu hỏi phỏng vấn Python với câu trả lời

Hơn 50 từ thông dụng phát triển web

Điều gì xảy ra sau khi ngoại lệ bị bắt Python?

Python có nhiều trường hợp ngoại lệ tích hợp được nêu ra khi chương trình của bạn gặp lỗi [một cái gì đó trong chương trình bị sai].Khi các trường hợp ngoại lệ này xảy ra, trình thông dịch Python dừng quy trình hiện tại và chuyển nó đến quá trình gọi cho đến khi nó được xử lý.Nếu không được xử lý, chương trình sẽ bị sập.the Python interpreter stops the current process and passes it to the calling process until it is handled. If not handled, the program will crash.

Bạn có thể sử dụng tiếp tục trong ngoại trừ không?

Để tránh điều này, hãy sử dụng câu lệnh tiếp tục trong khối ngoại trừ.Điều này bỏ qua phần còn lại của vòng lặp khi một ngoại lệ xảy ra.use the continue statement in the except block. This skips the rest of the loop when an exception occurs.

Chủ Đề