python fifo 是否必须用 os.open 读取?

Does a python fifo have to be read with os.open?

我正在尝试在 Python 中将 fifos 用于 IPC 例程,并使用以下代码来创建 fifo,然后启动两个线程在不同的时间写入它并不断地从中读取以打印出来放在 fifo 上的任何内容。

使用os.open()读取fifo时有效;但是,我正在阅读 O'Reilly 的 "Programming Python 4th Edition",他们声称可以通过 "consumer" 进程将 fifo 作为文本文件对象打开。

在这里,将 "consumer" 线程切换到目标 "consumer2" 函数尝试将 fifo 作为文本对象读取,而不是使用 os.open。但是这样读取的时候,调用"readline"方法的时候程序会卡住

有没有办法将 fifo 作为文本对象读入,还是必须始终使用 os.open 读入?

import os, time, threading

fifofile = '/tmp/thefifo'
if not os.path.exists(fifofile):
    os.mkfifo(fifofile)

def producer():
    num = 0
    fifo_out = os.open(fifofile, os.O_WRONLY) #open the fifo for writing
    while True:
        time.sleep(num)
        os.write(fifo_out, "".join(["Message  ",str(num)]).encode())
        num = (num + 1) % 5

def consumer():
    fifo_in = os.open(fifofile, os.O_RDONLY)
    while True:
        line = os.read(fifo_in, 24)
        print("Read: %s" % line.decode())

def consumer2():
    fifo_in = open(fifofile, "r") #open for reading as text object...
    while True:
        line = fifo_in.readline()[:-1] #read an available line on the fifo...
        print("Line read: %s" % line)

#Thread the calls...
producerTH = threading.Thread(target=producer)
consumerTH = threading.Thread(target=consumer) #using consumer2 does not work
producerTH.start()
consumerTH.start()

为此,我在 OS X 10.10.3.

中使用 Python 3.4.3

您只需要 os.write(fifo_out, "\n".encode()) 写完消息,因为 readline 需要“\n”