2013-09-25 88 views
0

我正在运行一个小型python脚本来检查每10秒,看看我的互联网访问是否可用(一直有我的isp吸吮问题)。我已经运行它大概2个月,它的工作完美,但现在它随机退出。有时会在我开始的20秒内退出,有时会等待5分钟。代码:退出Python网络错误代码和互联网连接

import time 
import datetime 
import urllib2 

waitTime = 300 
outfile = "C:\Users\simmons\Desktop\internetConnectivity.txt" 

def internetOffline(): 
    with open (outfile, "a") as file: 
     file.write("Internet Offline: %s\n" % time.ctime()) 
     print("Internet Went Down!") 

def internetCheck(): 
    try: 
     urllib2.urlopen('https://www.google.com', timeout = 2) 

    except urllib2.URLError: 
     internetOffline() 

while (1): 
    internetCheck() 
    time.sleep(10) 

我的问题不仅是,我将如何打印出退出时所发生的事情,而且也没有人知道这样做的更有效的方法,所以它可能会导致更少的网络交通。现在不是问题,但我只是想知道更有效的方法。

+0

你可以尝试检查它退出时产生错误信息? – justhalf

+0

如果你只是想看到一些错误,请尝试'sys.stderr = open(“error.txt”,“w”)'并在崩溃后检查文件。将需要运行权限可能。 – Leonardo

回答

2

,这可能是从去谷歌很多次我不是来确保

在你IDE中运行该程序,然后读取它抛出退出错误这应该告诉你什么或在程序退出

下面是做到这一点的好办法:

import urllib2 

def internet_on(): 
    try: 
     response=urllib2.urlopen('http://74.125.228.100',timeout=1) 
     return True 
    except urllib2.URLError as err: pass 
    return False 

74.125.228.100是google.com的IP-地址之一。更改http://74.125.228.100到任何网站可以预期迅速做出反应

我从this question这个解决方案,看看它,它应该帮助