python fifo必须与开放操作系统?

2024-10-02 02:25:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试在Python中使用fifo作为IPC例程,并使用以下代码创建fifo,然后启动两个线程,在不同的时间对其进行写入,并从中不断读取,以打印出fifo上的任何内容。在

当使用操作系统打开();然而,我正在阅读O'Reilly的“Programming Python 4th Edition”,他们声称fifo可以通过“consumer”进程作为文本文件对象打开。在

在这里,将“consumer”线程切换到“consumer2”函数将尝试将fifo作为文本对象读取,而不是使用操作系统打开. 但是,当以这种方式读取时,程序在调用“readline”方法时被阻塞。在

有没有办法把fifo作为文本对象读入,还是总是要在使用中读取开放操作系统?在

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()

为此,我在OSX10.10.3中使用Python3.4.3。在


Tags: the对象intrueconsumerosdefline

热门问题