Python中打开管道进行写操作卡住了

3
我可以为您提供翻译服务。以下是示例代码:

我有以下样本代码:

#! /usr/bin/python2.7
import os
import errno
FIFO = 'mypipe'

try:
    os.mkfifo(FIFO)
except OSError as oe: 
    if oe.errno != errno.EEXIST:
        raise
    with open(FIFO) as fifo:
        test=fifo.read()
        print("FIFO opened")
        while True:
            print "reading fifo"
            data = fifo.read()
            print "python read"
            if len(data) == 0:
                print("Writer closed")
                break
        print "about to open pipe for writing"
        otherpipe = open('mypipereader', 'r+')
        otherpipe.write('hello back!')

这可以正常工作。实际上,当将跟踪信息echo到管道中时,它确切地执行了我想要的操作,但由于某种原因,在另一个程序中尝试打开管道进行写入时,如下所示… … THEPIPE = open('mypipe', 'w') THEPIPE.write("hello!") 会持续挂起!有人曾告诉我这与内核无法在读取之前打开管道进行写入有关…是否有任何方法可以解决这个问题?
提前感谢您!

可能是如何在Python中正确写入FIFO的重复问题。 - undefined
请您提供一个MVEC,以演示问题所在。剪裁掉我们不需要的部分(例如,打开mypipereader),展示出实际客户端演示代码,并说明其未按照您预期的方式工作。(您可能会发现客户端的openwrite都成功了……) - undefined
1个回答

4

我曾经为此苦恼很久,最终通过先创建一个文件描述符来解决了我的问题:

import os

fifo = 'my-fifo'
os.mkfifo(fifo)

fd = os.open(fifo, os.O_RDWR) #non-blocking
f = os.fdopen(fd, 'w') #also non-blocking

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接