[英]Python – Breaking out of a deeply nested loop with `while`, `try`, `if`, and `except` statements
[英]Python - nested try statements in for loop - exit out of one and process next for statement
学习Python,并在此基础上加油。
有一个脚本可以连接到文件中提供的地址列表,并使用pexpect对每个地址执行操作。 我的问题是,如果出现登录错误,我希望它在将异常错误发送到日志后仅移至下一个地址。 它正在执行的操作是将父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 ')
如果嵌套的try遇到异常,我希望它一直移回for循环并从下一个地址开始。
我一直在研究与嵌套不同的退出语句,但似乎无法继续执行脚本,只能完全退出。
您可以在内部try-except块的except
部分中使用continue
语句。
范例-
>>> 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
尽管我建议最好只设置一个try-except块,然后在except块中,但根据引发的异常,您可以决定要记录/显示的错误。
如果您知道异常将是什么(对于每种情况,它将是一个不同的异常),则可以有多个例外,例如-
try:
<some logic>
except A: #handle error A
<handle error A>
except B:
<handle error B>
如果您不知道异常的名称(或者它们是相同的名称),则可以使用sys.exc_info()
获取有关异常的信息,它会返回三个元素的元组- (<type> , <value> , <Traceback>)
,您可以从中获取更多信息。 (请注意,建议不要向函数中的局部变量分配回溯,因为它会引起循环引用。
在内部except块的末尾添加一个continue语句:
for ip in ips:
try:
try:
<your code>
except:
<your code>
continue
except:
<your code>
因此,只要到达嵌套的except,它将开始遍历集合的下一个元素
好吧,我相当确定这是应该如何表现的。
您正在捕获异常,因此不会发生任何不良情况,并且执行正常进行。 我建议向孩子添加一个continue
, except
您只想在循环中继续前进。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.