如何在Python中创建一个写入FIFO,它将输出一行,然后等待下一次读取而不关闭?

时间:2017-07-15 11:46:29

标签: python raspberry-pi

我正在编写一个简单的python脚本,它将从Raspberry Pi Sense Hat中读取传感器,然后从文件系统中获取它们。

例如,当某些内容从<TEMPERATURE>:<HUMIDITY>:<PRESSURE>读取时,将返回信息/temp/sense

我有以下几点:

from sense_hat import SenseHat
import os

# Create a PIPE from which the readings can be read
path = "/tmp/sense"
os.mkfifo(path)

# Initialise the Sense Hat
sense = SenseHat()

with open(path, "w") as pipe:
   while True:
      sense.clear()

      temp = sense.get_temperature()
      sense.clear()
      humidity = sense.get_humidity()
      sense.clear()
      pressure = sense.get_pressure()

      # Output the information
      output = "%.3f:%.3f:%.3f" % (temp, humidity, pressure)

      pipe.write(output)
      pipe.flush()

fifo.close()

然而,当使用来自cat /tmp/sense的{​​{1}}时,这会持续输出相同读数的数据,例如:

pipe.flush()

我可以关闭FIFO,删除文件,重新创建它然后在每个循环上等待,但这似乎是错误的,因为有些东西可以从FIFO中读取,当它不在那里并且很重。我肯定必须有更好的方法,但我无法找到它是什么。

0 个答案:

没有答案