简体   繁体   English

Python-for循环中的嵌套try语句-退出其中一个并处理下一个for语句

[英]Python - nested try statements in for loop - exit out of one and process next for statement

Learning Python and grinding my gears on this one. 学习Python,并在此基础上加油。

Have a script that connects to a list of addresses provided form a file and preforms actions on each address with pexpect. 有一个脚本可以连接到文件中提供的地址列表,并使用pexpect对每个地址执行操作。 My issue is that if there is a login error, I want it to just move on to the next address after sending the exception error out to a log. 我的问题是,如果出现登录错误,我希望它在将异常错误发送到日志后仅移至下一个地址。 What it is doing is continuing down the parent try statement to the end, which is pointless since the script couldn't connect anyway: 它正在执行的操作是将父try语句一直延续到最后,这毫无意义,因为脚本无论如何都无法连接:

for ip in ips:
    try:
        try:
            #print curent address
            print "Connecting to " + ip
            #Login section
            c = pexpect.spawn('ssh -o StrictHostKeyChecking=no %s@%s' % (tacacsUser, ip))
            c.timeout = 10
            c.expect('password:')
            #Login to the device 
            c.expect('#')
        except Exception, e: #Write login errors to file
            print "Login error while connecting to " + ip
            saveLogs('LoginErrors.txt', e, 'Error connecting to ')


#send commands and such
    except Exception, e:
        print "Error occured while processing commands for " + ip
        saveLogs('ConfigErrors.txt', e, 'Error occured while processing ')

If the nested try hits the exception, I want it to move all the way back to the for loop and start with the next address. 如果嵌套的try遇到异常,我希望它一直移回for循环并从下一个地址开始。

I've been researching different exit statements from that nested except but can't seem to get the script to continue, only exit out completely. 我一直在研究与嵌套不同的退出语句,但似乎无法继续执行脚本,只能完全退出。

You can use continue statement in the except part of the inner try-except block. 您可以在内部try-except块的except部分中使用continue语句。

Example - 范例-

>>> for i in range(10):
...     try:
...             try:
...                     if i == 5:
...                             raise Exception
...             except:
...                     print("Reached 5")
...                     continue
...             print(i)
...     except:
...             print("Hmm")
...
0
1
2
3
4
Reached 5
6
7
8
9

Though I would advice that it would be better to have just one try-except block and in the except block, based on what exception is thrown you can decide what error to log/show. 尽管我建议最好只设置一个try-except块,然后在except块中,但根据引发的异常,您可以决定要记录/显示的错误。

If you know what the exception is going to be (and for each case it would be a different exception) , then you can have multiple excepts like - 如果您知道异常将是什么(对于每种情况,它将是一个不同的异常),则可以有多个例外,例如-

try:
    <some logic>
except A: #handle error A
    <handle error A>
except B:
    <handle error B>

If you do not know the names of the exceptions (or they are same names) , you can use sys.exc_info() to get the information about the exception , it returns a tuple of three elements - (<type> , <value> , <Traceback>) , and you can get more information from this. 如果您不知道异常的名称(或者它们是相同的名称),则可以使用sys.exc_info()获取有关异常的信息,它会返回三个元素的元组- (<type> , <value> , <Traceback>) ,您可以从中获取更多信息。 (Please note it is advised not to assign traceback to a local variable in a function as it causes cyclic references. (请注意,建议不要向函数中的局部变量分配回溯,因为它会引起循环引用。

Add a continue statement at the end of inner except block: 在内部except块的末尾添加一个continue语句:

    for ip in ips:
        try:
            try:
                <your code>
            except:
                <your code>
                continue
        except:
            <your code>

so whenever the nested except will be reached it will start iterating over next element of the collection 因此,只要到达嵌套的except,它将开始遍历集合的下一个元素

Well I'm fairly certain that is how it should behave. 好吧,我相当确定这是应该如何表现的。

You are catching the exception, so nothing bad happens, and the execution proceeds as normal. 您正在捕获异常,因此不会发生任何不良情况,并且执行正常进行。 I would recommend adding a continue into the child except if you want to just move on in the loop. 我建议向孩子添加一个continueexcept您只想在循环中继续前进。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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