2016-04-14 62 views
0

我正在爲自動過程編寫腳本。測試使用通過Paramiko的SSH連接,並且出於任何原因(與系統相關)系統重新啓動,這會關閉SSH連接。然後Python發出一個錯誤,表示連接被強制關閉。Python跳出異常聲明並繼續

我希望程序在except語句中捕獲錯誤,然後它將恢復ssh連接,然後從第一次出現錯誤的位置繼續。

的代碼太長髮布但本質上,我希望做到以下幾點:

try: 
     dotesting() 
except ParamikoError(): 
     restoressh() 
     #here i want to break out and get back into dotesting() 

我不知道這是可能因爲「GOTO」是在不使用皺起了眉頭在Python中。我會如何執行此操作?

編輯
所以我最初想做的是不可能的。現在我正在把重點轉向重新啓動的一個具體步驟中dotesting()

def dotesting(): 
     try: 
      stepone() 
     except ParamikoError(): 
      #Need to restart step here, want to flow into steptwo() below 
     try: 
      steptwo() 
     except ParamikoError(): 
      #Need to restart step here, want to flow into the return statement below 
     return("Success") 
+0

你不能回到異常出現的地方,沒有。您最多可以*重新啓動*'dotesting()'。只需使用一個循環。 –

+3

否則,您必須重構'dotesting()'以打破通過SSH運行的步驟,以便您可以在每個步驟捕獲異常並重新啓動該步驟。 –

+0

@MartijnPieters這是有道理的。我已經更新了該問題以反映您已提出的建議,因爲這可以適用於我的案例 – bladexeon

回答

0

一個非常糟糕的答案就是編寫程序,然後將其保存爲一個字符串列表,其中列表中的每個項目爲你的程序的行。然後做類似如下:

i =0 
while i<len(program) 
try: 
    eval(program[i]) 
    i+=1 
except ParamikoError(): 
    pass 

就像我說的,非常糟糕的解決方案,但我想不出任何更好的。

+0

爲什麼選擇字符串?爲什麼不能使用對象?只要把它們放在一個列表中,然後調用每一個,並傳入ssh連接。 –

0

如果每次你不應該拋出異常模擬SSH接口。否則,你可以這樣做:

def stepone(): 
    raise AttributeError 

def steptwo(): 
    return 1 

class TestStuff(unittest.TestCase): 

    def test_steps(self): 
     with self.assertRaises(AttributeError): 
      stepone() 
     self.assertEquals(steptwo(), 1) 

if __name__ == '__main__': 
    unittest.main()