Poco,子进程通信异常(python解释器为子进程)

我想与python和lua脚本通信,但是python的表现不如预期。Python挂起:

日志:

lua << 'hello!',   lua >> 'hello!'
lua << 'hello!',   lua >> 'hello!'
lua << 'hello!',   lua >> 'hello!'
python << 'hello!',

主C++应用程序:

#include <iostream>
#include "Poco/Process.h"
#include "Poco/PipeStream.h"
void test( char const* interpreter, char const* filename )
{
   std::vector<std::string> args { filename };
   Poco::Pipe outPipe;
   Poco::Pipe inPipe;
   Poco::ProcessHandle process_handle = Poco::Process::launch( interpreter, args, &inPipe, &outPipe , nullptr/*errPipe*/ );
   Poco::PipeInputStream output_reader(outPipe);
   Poco::PipeOutputStream input_writer(inPipe);
   for(int repeat_counter=0; repeat_counter<3; ++repeat_counter)
   {
      auto send_str("hello!");
      input_writer << send_str << std::endl;
      std::cout << interpreter << " << '" << send_str << "',   " );
      std::cout.flush();
      std::string receiv_str;
      output_reader >> receiv_str;
      std::cout << interpreter << " >> '" << receiv_str << "'" << std::endl;
   }
}
int main()
{
   test("lua","test.lua");
   test("python","test.py");
   return 0;
}

Lua脚本:

for i=1,10 do
   print(io.read())
end

Python脚本:

for i in range(0,10):
   print(raw_input())

在终端中,两个脚本的表现相同。

解决方案:对于Python,必须仅使用sys.stdout.writeflush,感谢@greatwolf。

点赞
用户234175
用户234175

我的猜测是,Python 的 print 函数并不会直接输出到标准输出,或者背后发生了一些妙事。试试使用 sys.stdout.write 替换它。别忘了先导入 sys 模块。

2016-12-29 03:31:32