![](/img/trans.png)
[英]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.