Python 从命名管道读取连续数据

Python 从命名管道读取连续数据,python,c++,ipc,named-pipes,fifo,Python,C++,Ipc,Named Pipes,Fifo,我一直在尝试从命名管道读取连续数据。但出于某种原因,如果我不延迟,接收器将停止读取,在几个样本之后,只显示一个空白屏幕 我需要发送可能以毫秒为单位发生变化的连续数据,这就是延迟不起作用的原因。我试图首先使用while循环来模拟它(真正的脚本将读取金融数据)。这是我第一次尝试: 这是发送者,一个python脚本: import os import time try: os.remove("/tmp/pipe7") # delete except: print "Pipe a

我一直在尝试从命名管道读取连续数据。但出于某种原因,如果我不延迟,接收器将停止读取,在几个样本之后,只显示一个空白屏幕

我需要发送可能以毫秒为单位发生变化的连续数据,这就是延迟不起作用的原因。我试图首先使用while循环来模拟它(真正的脚本将读取金融数据)。这是我第一次尝试:

这是发送者,一个python脚本:

import os
import time

try:
    os.remove("/tmp/pipe7")    # delete
except:
    print "Pipe already exists"
os.mkfifo("/tmp/pipe7")    # Create pipe
x = 0
while True:
    x = time.time()
    pipe = open("/tmp/pipe7", "w")
    line = str(x) + "\r\n\0"
    pipe.write(line)
    pipe.close()

    #time.sleep(1)


os.remove("/tmp/pipe7")    # delete
这是C/C++中的接收器:

#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <iostream>

#include <sys/stat.h>

#define MAX_BUF 1024


using namespace std;

int main()
{

    while(1){

        char buf[MAX_BUF];
        memset (buf, 0, sizeof(buf)); //Clearing the message buffer
        int fd = open("/tmp/pipe7", O_RDONLY);  // Open the pipe
        read(fd, buf, MAX_BUF);                         // Read the message - unblock the writing process
        cout << buf << endl;
        close(fd);                                 // Close the pipe

    }
    return 0;
}
#包括
#包括
#包括
#包括
#包括
#定义最大值为1024
使用名称空间std;
int main()
{
而(1){
char buf[MAX_buf];
memset(buf,0,sizeof(buf));//清除消息缓冲区
int fd=open(“/tmp/pipe7”,ordonly);//打开管道
read(fd,buf,MAX_buf);//读取消息-取消阻止写入过程

cout首先,不需要为每个I/O操作打开/关闭管道。不过,最终可能需要在每次写入后刷新输出

然后,当您输出基于行的文本数据时,您不能真正依靠固定宽度的读取来获取数据。根据您的示例,我只需读取一个字符串-
istream
应该一直读取到下一个空格(此处
\n\r

所有这些都会导致类似的情况(未经测试——小心拼写错误!):


std::ifstream管道(“/tmp/pipe7”);//打开管道
而(1){
字符串istr;
管道>>istr;

cout
被重载以从istream读取字符串。在这种情况下,它将从流中提取字符,并在遇到空白字符或流结束时立即停止。广义上说,这允许“逐字”回读输入.

我想知道为什么每次读/写一行时都需要打开和关闭管道?也许你缺少file对象的
flush
方法?@SylvainLeroux:这肯定是个问题,因为管道逻辑绑定到可用的读写器。我尝试过每次都不关闭管道,但似乎仍然没有解决这个问题。我没有太多的管道或套接字编程经验。所以我很难找出问题所在。太棒了,这很有效。你能详细介绍一下如何将管道中的数据读入字符串吗?read()方法不接受字符串,对吗?Nvm我刚刚看到您使用ifstream进行编辑。非常感谢,这很好!!谢谢。再问一个问题。在这种情况下使用istream不会影响性能,对吗?我看到数据在打印到屏幕上时会慢很多。@Lui只是一个随机猜测,可能“慢”与缓冲区有关。请尝试。
with open("/tmp/pipe7", "w") as pipe:
    while True:
        x = time.time()
        line = str(x) + "\r\n"
        pipe.write(line)
        pipe.flush()
        # in real code, should somehow break the loop at some point
std::ifstream  pipe("/tmp/pipe7");  // Open the pipe
while(1){
    std::string istr;

    pipe >> istr;        
    cout << istr << endl;
    # In real code, should somehow break the loop at some point
}

close(fd);