【问题标题】:Piping EOF problems with stdio and C++/Python使用 stdio 和 C++/Python 处理 EOF 问题
【发布时间】:2010-03-14 20:43:31
【问题描述】:

我在 python 进程和 C++ 程序之间的通信管道中遇到了一些 EOF 和 stdio 问题。我不知道我做错了什么。当我在程序中看到 EOF 时,我清除了标准输入,下一轮我尝试在新行中读取。问题是:由于某种原因,getline 函数立即(从第二次运行开始,第一次按预期工作)返回一个 EOF 而不是等待来自 python 进程的新输入......知道吗?

好的,代码如下:

#include <string>
#include <iostream>
#include <iomanip>
#include <limits>

using namespace std;

int main(int argc, char **argv) {
    for (;;) {
        string buf;
        if (getline(cin,buf)) {
            if (buf=="q") break;
            /*****///do some stuff with input //my actual filter program
            cout<<buf;
            /*****/
        } else {
            if ((cin.rdstate() & istream::eofbit)!=0)cout<<"eofbit"<<endl;
            if ((cin.rdstate() & istream::failbit)!=0)cout<<"failbit"<<endl;
            if ((cin.rdstate() & istream::badbit)!=0)cout<<"badbit"<<endl;
            if ((cin.rdstate() & istream::goodbit)!=0)cout<<"goodbit"<<endl;
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max());

            //break;//I am not using break, because I
                    //want more input when the parent
                    //process puts data into stdin;
        }
    }

    return 0;
}

在python中:

from subprocess import Popen, PIPE
import os
from time import sleep

proc=Popen(os.getcwd()+"/Pipingtest",stdout=PIPE,stdin=PIPE,stderr=PIPE);

while(1):
  sleep(0.5)

  print proc.communicate("1 1 1")
  print "running"

【问题讨论】:

    标签: c++ python pipe stdin iostream


    【解决方案1】:

    communicate 在 python 中是一个一次性函数。它将给定的输入发送到进程,关闭输入流,然后读取输出流,等待进程终止。

    “通信”后,您无法使用相同的进程“重新启动”管道。

    相反,在管道的另一端,当您读取EOF 时,没有更多数据要读取。任何读取尝试都会立即返回EOF; python已经关闭了管道。

    如果你想继续与同一个管道进行通信,你需要使用子进程的 stdinstdout 成员而不是 communicate(但要小心死锁的可能性)并使用除流的结尾表示 C++ 端应该进行另一“批处理”。

    【讨论】:

      猜你喜欢
      • 2012-06-25
      • 2011-08-11
      • 2019-02-07
      • 1970-01-01
      • 1970-01-01
      • 2013-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多