打开一个用Python写的管道是挂着的

2024-05-19 13:32:16 发布

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

我有以下示例代码:

#! /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!')

这个很好用。事实上,当回送跟踪到管道中时,它确实做了我想要它做的事情,但是由于某种原因,当我试图打开管道,以便在另一个程序中编写时,比如。。。。在

THEPIPE = open('mypipe', 'w')THEPIPE.write("hello!")

它继续挂着!有人曾经告诉我,这和内核在读之前不能打开写管道有关。。。我有什么办法可以避开这个问题吗?在

提前谢谢你!在


Tags: importreaddataif管道osasopen
1条回答
网友
1楼 · 发布于 2024-05-19 13:32:16

我一直在努力解决这个问题,最终通过首先创建一个文件描述符来解决我的问题:

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

相关问题 更多 >