Python中带有无限结尾代码的MemoryError
我正在尝试编写一个Python程序,该程序在后台无限期运行(直到用户停止),并检测网页的任何更改。因此,我对页面内容进行散列,并与之前的散列进行比较,如果值发生变化,则我知道页面已发生变化。这是我的密码:Python中带有无限结尾代码的MemoryError,python,memory,hash,monitor,Python,Memory,Hash,Monitor,我正在尝试编写一个Python程序,该程序在后台无限期运行(直到用户停止),并检测网页的任何更改。因此,我对页面内容进行散列,并与之前的散列进行比较,如果值发生变化,则我知道页面已发生变化。这是我的密码: import requests import threading import hashlib from urllib.request import urlopen URL = 'https://www.bbc.co.uk/sport/live/football/55864099' hea
import requests
import threading
import hashlib
from urllib.request import urlopen
URL = 'https://www.bbc.co.uk/sport/live/football/55864099'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36'}
current_hash = 'Initial'
def monitor():
threading.Timer(5, monitor).start() #The number in the Timer() bracket represents the scheduling interval in seconds
response = urlopen(URL).read()
new_hash = hashlib.sha224(response).hexdigest()
global current_hash
if(current_hash == new_hash):
print('same')
else:
print('different')
current_hash = new_hash
monitor()
但是,在运行几分钟后,我在控制台中遇到以下错误:
MemoryError
但有时程序会在短暂延迟后继续。在我继续进行的过程中,是否有任何方法可以清除内存以防止发生此错误?在python文档中,如果某个内容有关闭,您应该调用close,或者干脆清除内存错误,或者任何需要清理的资源。只有在阅读close()方法背后的源代码并确定它不起任何作用后,才能真正跳过调用close
with urllib.request.urlopen('http://www.python.org/') as f:
... print(f.read(300))
您还应该遵循指数退避,固定间隔轮询只是让您的CPU保持温暖并缩短其寿命,一个库可以做到这一点:您是否认真地用每秒10个请求轰炸服务器?如果一个请求需要超过100毫秒才能完成,您将开始并行运行越来越多的线程…!我意识到这有点极端,所以我将间隔设置为5秒(并更改了最初的问题以反映这一点),现在我还没有出现错误弹出,但我觉得如果我一次运行几个小时,它可能会弹出,因此我仍然希望防止出现这种情况。我将对此进行调查,谢谢。