我正在尝试学习 python。这是我编写的用于检查互联网连接的脚本
import os
import urllib2
from time import sleep
REMOTE_SERVER = "www.google.co.uk"
def is_connected():
try:
# see if we can resolve the host name -- tells us if there is
# a DNS listening
host = socket.gethostbyname(REMOTE_SERVER)
# connect to the host -- tells us if the host is actually
# reachable
s = socket.create_connection((host, 80), 2)
return True
except:
pass
return False
while(1):
if is_connected() == False:
print is_connected()
sleep(10)
问题是即使我已连接到互联网,此脚本也会返回 false。我可以 ping www.google.co.uk 但这个脚本只返回 false。有什么想法吗???
请您参考如下方法:
因为您还没有导入socket,您对socket.gethostbyname 的引用将失败并出现NameError。但是您正在捕获并消除 try/except block 中的每一个异常,包括那个错误。除了一开始,你永远不应该做空白,尤其是永远不要只是让 pass。
删除 try/except,或将其限制为您知道可以处理的异常。
