繁体   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