繁体   English   中英

Linux。 蟒蛇。 从命名管道读取

[英]Linux. Python. Read from named pipe

我在复制python中的某些功能时遇到问题。
在ubuntu下工作。
我有一个用c ++编写的程序,它可以填充内容,并且偶尔将格式化的数据写入命名管道。 我也有一个从该命名管道读取的c ++程序。 那里没有问题。 但是,我几乎不知道如何在python中复制相同的东西(只有阅读部分)。

这是我用来阅读的C ++代码:

//various includes
#define FIFO_NAME "/tmp/MYFIFO"

using namespace std;

int main()
{
    int fp;
    fp = open(FIFO_NAME, O_RDONLY);
    char readbuf[80];
    while (true)
    {
        int tot = 0;
        //read an int to know how many results are there to read right now
        while(tot<sizeof(int))
            tot+= read(fp, readbuf+tot, sizeof(int)-tot);
        int nres = *(int *)&readbuf[0];
        if (nres>0)
        {
            cout << nres << " results:" << endl;
            for (int i = 0; i < nres; i++)
            {
                //here I read 3 floats
            }
        }
    }
}

此c ++代码完全按我的要求运行:它从命名管道读取字节,将它们转换为相应的数字,使它们可供我使用。
我试图在python中做同样的事情,但是失败了。
首次尝试使用python代码:

import os
import time

FIFO_NAME = '/tmp/MYFIFO'

def main():
    fp = os.open(FIFO_NAME, os.O_RDONLY)
    while True:
        time.sleep(0.001)
#Here I just try to read the first 4 bytes (the initial int) and fail already
        line = os.read(fp, 4) #I think this would read 4 bytes from the FIFO?
        print(len(line)) #ALWAYS prints 4
        print(line) #ALWAYS prints a blank line
        print(int(line)) #this of course gives an error, saying that line ==''

第二次尝试使用python代码(给出相同的错误结果):

import os
import time

FIFO_NAME = '/tmp/MYFIFO'

def main():
    fp = open(FIFO_NAME, 'r')
    while True:
        time.sleep(0.001)
#Here I try to read up to the line break
        line = fp.readline() #I think this would read to the line break, but it actually returns immediately
        print(len(line)) #after the first few iterations, this always prints 6
        print(line) #ALWAYS prints a blank line

在第二次尝试中,我希望阅读第一个换行符(我可以很容易地让C ++生产者在每个“数据包”的末尾放置一个换行符)。 但是,这总是读取空行。

我的问题是关于在python中获得我在c ++中具有的功能。 我可以通过两种方式看到这种情况:

  • 通过像在c ++中一样实际读取字节并将其编组为正确的数据类型和值,来固定我在python端使用管道的方式。
  • 让python“加载”一个字节缓冲区,直到收到换行符,然后从那里提取我的数字。

无论哪种方式,我都不明白为什么read和readline返回这些空白字符串,也不知道如何处理它们。

我希望你们中的一些可以帮助我。 随时要求澄清和更多信息。

在我的评论中,我指的是python,但这是by。
仔细研究一下,可能会对您有所帮助,因为它特别涉及“ C#和Python之间的命名管道”。
http://jonathonreinhart.blogspot.co.uk/2012/12/named-pipes-between-c-and-python.html

万一链接丢失了,这是乔纳森所说的:

C#

// Open the named pipe.
var server = new NamedPipeServerStream("NPtest");

Console.WriteLine("Waiting for connection...");
server.WaitForConnection();

Console.WriteLine("Connected.");
var br = new BinaryReader(server);
var bw = new BinaryWriter(server);

while (true) {
    try {
        var len = (int) br.ReadUInt32();            // Read string length
        var str = new string(br.ReadChars(len));    // Read string

        Console.WriteLine("Read: \"{0}\"", str);

        str = new string(str.Reverse().ToArray());  // Just for fun

        var buf = Encoding.ASCII.GetBytes(str);     // Get ASCII byte array     
        bw.Write((uint) buf.Length);                // Write string length
        bw.Write(buf);                              // Write string
        Console.WriteLine("Wrote: \"{0}\"", str);
    }
    catch (EndOfStreamException) {
        break;                    // When client disconnects
    }
}

Console.WriteLine("Client disconnected.");
server.Close();
server.Dispose();

蟒蛇

import time
import struct

f = open(r'\\.\pipe\NPtest', 'r+b', 0)
i = 1

while True:
    s = 'Message[{0}]'.format(i)
    i += 1

    f.write(struct.pack('I', len(s)) + s)   # Write str length and str
    f.seek(0)                               # EDIT: This is also necessary
    print 'Wrote:', s

    n = struct.unpack('I', f.read(4))[0]    # Read str length
    s = f.read(n)                           # Read str
    f.seek(0)                               # Important!!!
    print 'Read:', s

    time.sleep(2)

在此示例中,我实现了一个非常简单的协议,其中每个“消息”都是4个字节的整数(C#中的UInt32,Python中的“ I”(解压缩)格式),它指示后面的字符串的长度。 字符串是ASCII。 这里要注意的重要事项:

Python open()的第三个参数表示“未缓冲”。
否则,它将默认为行缓冲,这意味着它将在通过管道实际发送换行符之前等待换行符。

我不确定为什么,但是省略seek(0)会导致IOError#0。
我被一个StackOverflow问题所吸引。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM