How to know when a C ++ program is waiting for input?

I am trying to control a simple C ++ program through python. The program works by asking the user for input. Requests do not necessarily end. I would like to know if there is a way from python to say that the C ++ program no longer generates output and switches to an input request. Here is a simple example:

C ++

#include <iostream>

using namespace std;

int main()
{
    int x;
    cout << "Enter a number ";
    cin >> x;
    cout << x << " squared = " << x * x << endl;
}

python:

#! /usr/bin/python
import subprocess, sys
dproc = subprocess.Popen('./y', stdin=subprocess.PIPE,stdout=subprocess.PIPE, stderr=subprocess.PIPE)
while (True) :
    dout = dproc.stdout.read(1)
    sys.stdout.write(dout)
    dproc.stdin.write("22\n")

This kind of work, but writes too much for dproc.stdin. Instead, I'm looking for a way to read everything from dproc.stdout until the program is ready for input, then write dproc.stdout.

If possible, I would like to do this without changing the C ++ code. (However, I tried playing with buffering on the C ++ side, but it didn't seem to help)

Thanks for any answers.

+3
2

, . , , . :

  • / , : , ..
  • , : .

, , . , . pexpect - Python, .

+6
+3

Source: https://habr.com/ru/post/1775263/


All Articles