NEW:
它在没有isseus的情况下工作了40分钟,然后代码本身崩溃了: 这是控制台中的outpud
Gradi: 29.0 C Umidita: 35.0 %
Traceback (most recent call last):
File "temp.py", line 22, in <module>
valori='Gradi: {0:0.1f} C Umidita: {1:0.1f} %'.format(temperature, humidity)
ValueError: Unknown format code 'f' for object of type 'str'
你有什么建议吗?
OLD:
我必须刷新每次由Python脚本重写的HTML页面以获得最新值。有时会发生页面刷新但显示白页,没有数据。我该如何解决这个问题?
import datetime
import sys
import Adafruit_DHT
import time
a = """<html>
<meta http-equiv="refresh" content="">
<head></head>
<body><p>"""
b = """</p></body>
</html>"""
try:
while True:
file = open("logtemperature.txt", "a")
web = open('temperatura.html', 'w')
humidity, temperature = Adafruit_DHT.read_retry(11, 16) #11 modello 16 pin
valori = 'Gradi: {0:0.1f} C Umidita: {1:0.1f} %'.format(temperature, humidity)
print (valori)
file.write("\n" + valori + " " + str(datetime.datetime.now()))
web.write(a + "TEMPERATURA INTERNA:" + " " + valori + b)
time.sleep(1)
web.close()
file.close()
time.sleep(2)
except KeyboardInterrupt:
file.close()
web.close()
答案 0 :(得分:0)
为了使确实确保文件永远不会是空的或不完整的,当用另一个程序读取文件时,请继续阅读第一个代码块下面。
如果您可以几乎从不拥有空文件或不完整的文件,那么
import datetime
import sys
import Adafruit_DHT
import time
a="""<html>
<meta http-equiv="refresh" content="">
<head></head>
<body><p>"""
b="""</p></body>
</html>"""
while True:
humidity, temperature = Adafruit_DHT.read_retry(11,16) #11 modello 16 pin
valori='Gradi: {0:0.1f} C Umidita: {1:0.1f} %'.format(temperature, humidity)
print (valori)
ls="\n"+valori+" "+str(datetime.datetime.now())
with open("logtemperature.txt","a") as file:
file.write(ls)
ws=a+"TEMPERATURA INTERNA:"+" "+valori+b
with open('temperatura.html','w') as web:
web.write(ws)
time.sleep(2)
如果您使用的是Unix / Linux(例如Raspbian),您可以创建自己的准原子写,因为os.rename是原子的,确保temperatura.html
始终完整
import os
def atomic_write(filename, bytes):
shouldnotexist=filename+".deleteme"
with open(shouldnotexist,"wb") as f:
f.write(bytes)
os.rename(shouldnotexist,filename)
替换
with open('temperatura.html','w') as web:
web.write(ws)
带
atomic_write('temperatura.html', ws)
在Windows上它可能更复杂......
编辑:
要缓解ValueError问题,可以替换
valori='Gradi: {0:0.1f} C Umidita: {1:0.1f} %'.format(temperature, humidity)
带
try:
valori='Gradi: {0:0.1f} C Umidita: {1:0.1f} %'.format(temperature, humidity)
except ValueError:
valori='Gradi: {0} C Umidita: {1} % (something saying there was a problem)'.format(temperature, humidity)