python - 在 tmux 中运行脚本时用 python 写入传感器读出
问题描述
抱歉,如果以前有人问过这个问题,但我找不到我正在寻找的解决方案/信息。
所以:我正在运行一个带有 python 脚本的树莓派 0W,它读取 4 个温度传感器,监控家里的一些东西。我每 2 分钟读取一次这些传感器,并将输出写入 CSV(暂时对我来说足够了)。当我 ssh 我的 PI 并在 TMUX 中运行我的脚本时,我意识到当我调用我的“Sensordata.csv”时,它只会在我关闭我的 TMUX 会话中的脚本时更新。理想情况下,我希望在每个轮询周期后更新我的“Sensordata.CSV”文件。
我相信它不是代码,因为我的代码在 shell 中正常运行时会打开、写入和关闭文件。希望有人可以帮助我=)
import time
import csv
from datetime import datetime
def get_temp(dev_file):
f = open(dev_file,"r")
contents = f.readlines()
f.close()
index = contents[-1].find("t=")
if index != -1 :
temperature = contents[-1][index+2:]
cels =float(temperature)/1000
return cels
time_for_csv=time.asctime( time.localtime(time.time()))
f=open("Sensordata.csv", "a")
c=csv.writer(f)
if __name__ =="__main__":
while True:
dateTimeObj = datetime.now()
timestampStr = dateTimeObj.strftime("%d-%b-%Y (%H:%M:%S.%f)")
temp = get_temp("//sys/bus/w1/devices/28-0301a2799ec4/w1_slave")
temp2 = get_temp("//sys/bus/w1/devices/28-0301a2790081/w1_slave")
temp3 = get_temp("//sys/bus/w1/devices/28-012020be268d/w1_slave")
tempout = get_temp("//sys/bus/w1/devices/28-00000b0f6540/w1_slave")
print('Current Timestamp : ', timestampStr, "28-00000b0f6540 - Outside Sensor", tempout)
print('Current Timestamp : ', timestampStr, "28-0301a2799ec4 - Floorheating out", temp)
print('Current Timestamp : ', timestampStr, "28-0301a2790081 - Floorheating in", temp2)
print('Current Timestamp : ', timestampStr, "28-012020be268d - Room Sensor", temp3)
f = open("Sensordata.csv", "a")
c = csv.writer(f)
c.writerow([timestampStr, temp, temp2, temp3, tempout])
f.close()
time.sleep(120)
解决方案
我不认为 Tmux 是问题的一部分。
尝试在脚本中删除这 3 行代码:
time_for_csv=time.asctime( time.localtime(time.time()))
f=open("Sensordata.csv", "a")
c=csv.writer(f)
time_for_csv
未使用。
打开文件进行写入或追加时,更安全的方法是使用以下内容:
with open("Sensordata.csv", "a") as f:
c=csv.writer(f)
c.writerow([timestampStr, temp, temp2, temp3, tempout])
即使引发异常,文件对象也将始终关闭。您不必明确关闭它。请参阅Python 中的 With 语句
我猜你在脚本中间打开一个文件对象会打开一个文件,然后你f
在if __name__ == "__main__
. 让文件对象保持打开状态可能会产生不可预知的结果,就像您正在经历的那样。
推荐阅读
- flutter - 在颤抖中我尝试调用:_addfromInteger
- apache-spark - 当列中的任何一个具有空值时,如何连接多个列
- flutter - 无法在颤动的单个滚动视图中添加不同的小部件
- angular - VS 代码在 HTML 行的末尾添加分号
- javascript - 即使没有准备好,Safari 上的 JavaScript 似乎也会使用资源
- mesos - 阻止连接到节点 DC/OS mesos dcos_l4lb_mgr:agents/3:505: L4LB 无法访问代理节点,大小:1,[{XX,XX,XX,XXX}]
- laravel - 如何删除或销毁多态关系laravel?
- multithreading - Blazor Wasm HttpClientInterceptor 线程问题
- html - 针对没有类或 ID 的特定段落的 CSS
- docker - 在 docker 中检索容器启动顺序