python子进程与c ++程序

时间:2015-10-22 18:05:07

标签: python c++ subprocess ipc

是否可以使用python子进程与使用read() from unistd.h的C ++程序进行通信?运行C ++程序时,输入的数据将存储在文件中。当我从python中调用它并尝试写入数据时,它似乎无法捕获它。

python代码

#!/usr/bin/env python3
import sys
import pdb
import subprocess
import time

proc = subprocess.Popen(['./std.bin'],stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,shell=True)

time.sleep(1)
for  cnt in range(100):
    proc.stdin.write(b'test1\ntest2\n')
    proc.stdin.flush()

proc.stdin.write(b"qq")

C ++程序

#include <termios.h>
#include <map>
#include <iostream>
#include <stdlib.h>
#include <unistd.h>
#include <sstream>
#include <string>
#include <fstream>

std::ofstream file_out;
volatile bool ctrlc_pressed = false;

static std::string readline(int fd)
{
  struct termios tios;
  bool noncanonical = tcgetattr(fd, &tios) == 0 && (tios.c_lflag & ICANON) == 0;

  std::string s;
  for (char ch; read(fd, &ch, 1) == 1; )
  {
    if (ch == '\x7f')
    {
      if (s.empty())
        continue;
      s.erase(s.end()-1);

      if (noncanonical && write(fd, "\b \b", 3) != 3)
        ; // shut up gcc
    }
    else if (noncanonical && write(fd, &ch, 1) != 1)
      ; // shut up gcc

    if (ch == '\n')
      break;
    if (ch != '\x7f')
      s += ch;
  }
  return s;
}

int main()
{
    file_out.open("out.txt");
    file_out<<"Started\n"<<std::flush;

  while (1)
  {
    std::cerr << ": " << std::flush;
    std::string s = readline(2);
    std::stringstream ss(s);
    std::string cmd, tmp;

    if (!(ss >> cmd))
    {
      continue;
    }
    if(cmd.find('q')!=std::string::npos) return 0;

    std::cout<<cmd;
    file_out<<cmd<<std::flush;
    while (ss >> tmp)
      {
        std::cout<<' '<<tmp;
        file_out<<' '<<tmp<<std::flush;
    }

    file_out<<'\n'<<std::flush;  

    std::cout<<'\n'<<std::flush;

  }
return 0;

}

0 个答案:

没有答案