具有无限循环的 Python 代码在网页抓取时卡住了,没有错误消息



我有一个python代码,它从url中获取数据,并在每15秒内将其写入文件。一段时间后,代码停止写入。但是,它似乎仍然有效。它不会给出任何错误消息。停止所需的时间各不相同。有时,需要一周时间才能停止。有时,一天。这是我的代码:

import urllib
import time
import datetime
def temp_check():
  url = "http://172.16.1.145/"  #50kw air conditioner
  try:
     f = urllib.urlopen(url)
     data = f.read()
     values50Kw = re.findall(r'<Value valueType="6" precision="1">(.*?)</Value>', str(data))
     Treturn_air50Kw= float(values50Kw[3])
  except:
     Treturn_air50Kw = 0.0
     print (datetime.datetime.now().strftime("%d-%m-%Y %H:%M:%S") + ' 50kw Temp data could not be obtained and set to be 0.0 ')
  with open("temp_data.txt", "a") as iwf:
        iwf.write(datetime.datetime.now().strftime("%d-%m-%Y %H:%M:%S") + " " + str(Treturn_air50Kw))
        iwf.write("n")
        iwf.close()
while True:
  temp_check()
  time.sleep(15)

这里

except Exception as exception:
   print("Error encountered", exception)
   Treturn_air50Kw = 0.0
   print (datetime.datetime.now().strftime("%d-%m-%Y %H:%M:%S") + ' 50kw Temp data could not be obtained and set to be 0.0 ')

您应该打印异常或记录它以查看遇到的错误类型,而不仅仅是打印一些信息

最新更新