簡體   English   中英

Python沒有捕獲異常

[英]Python not catching exceptions

我有這個腳本:

#!/usr/bin/env python
#import needed modules
import telnetlib
import time
#define variables
HOST = "xxxxxx"
user = "xxxxxx"
password = "xxxxxx"
#open telnet connection
tn = telnetlib.Telnet(HOST, 10800)
time.sleep(2)
#check for initial screen and press enter to go to login
tn.read_until("Device")
tn.write("\r\n")
time.sleep(2)
#Wait for username prompt and enter user/pass
try:
  tn.read_until("User Name:",5)
except:
  #Timeout looking for Username prompt
  print "CRITICAL: User Name prompt never arrived"
  exit(2)
tn.write(user + "\r\n")
tn.read_until("Password :")
tn.write(password + "\r\n")
time.sleep(2)
#wait for logout prompt
try:
  tn.read_until("7<Logout               >",5)
except:
  #Timeout looking for successful login
  print "CRITICAL: Did not login successfully"
  exit(2)

#Logout and close connection
tn.write("7\r")
tn.close()

#Exit with success
print "OK: Test login to MWA Succeeded"
exit(0)

不管我做什么,都不會發現任何例外。 我將read_until更改為“ User Name:”,只是一些垃圾字符,但它仍停留在代碼末尾。 我希望我只是在做一些非常愚蠢的事情,而不是telnetlib的問題。

謝謝!

根據文檔

讀取直到遇到給定的預期字符串或超時秒數為止。

如果找不到匹配項,則返回任何可用的內容,可能是空字符串。 如果連接已關閉並且沒有可用的數據,則引發EOFError。

檢查try塊中的返回值,如果該值不符合您的期望,請自行raise以觸​​發except情況。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM