退出和internet连接时的Python错误代码

退出和internet连接时的Python错误代码,python,networking,python-2.7,error-handling,Python,Networking,Python 2.7,Error Handling,我正在运行一个小python脚本,每10秒检查一次,看看我的互联网接入是否可用(我的isp出现问题)。我已经运行了大概2个月,它工作得很好,但现在它随机退出。有时它会在我启动后20秒内退出,有时它会等待5分钟。代码是: import time import datetime import urllib2 waitTime = 300 outfile = "C:\Users\simmons\Desktop\internetConnectivity.txt" def internetOfflin

我正在运行一个小python脚本,每10秒检查一次,看看我的互联网接入是否可用(我的isp出现问题)。我已经运行了大概2个月,它工作得很好,但现在它随机退出。有时它会在我启动后20秒内退出,有时它会等待5分钟。代码是:

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 )

我的问题不仅是,当它退出时,我将如何打印出正在发生的事情,而且,是否有人知道一种更有效的方法来执行此操作,因此它可能会导致更少的网络流量。现在这不是问题,但我只是想知道更有效的方法

这可能是从谷歌到很多次我都不确定

在您的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任何可以快速响应的站点


我从中得到这个解决方案,看看它,它应该会有帮助

您可以尝试检查它退出时产生的错误消息?如果您只是想看到一些错误,请尝试
sys.stderr=open(“error.txt”,“w”)
并在崩溃后检查文件。可能需要使用权限运行。