Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I tell when a c++ program is waiting for input?

Tags:

c++

python

cout

cin

I'm trying to control a simple c++ program through python. The program works by prompting the user for input. The prompts are not necessarily endl terminated. What I would like to know is if there is a way to tell from python that the c++ program is no longer generating output and has switched to requesting input. Here's an 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 sort of works but writes to dproc.stdin too much. What I am looking for instead is a way to read everything from dproc.stdout until the program is ready for input and then write to dproc.stdout .

If possible, I would like to do this w/o modifying the c++ code. ( However, I have tried playing with buffering on the c++ side but it didn't seem to help )

Thank you for any responses.

like image 879
Dave Compton Avatar asked Jan 25 '26 05:01

Dave Compton


1 Answers

I'm not aware of a sufficiently general paradigm for detecting that the remote end is waiting for input. I can think of basic ways, but also of situations in which they will fail. Examples:

  1. Read with a non-blocking pipe/socket until no input arrives: the response might be interrupted by the process writing to disk, waiting for a reply from a database etc.
  2. Wait until the process becomes idle: a background thread might still be running.

You'll have to be aware of the protocol used by the application you're trying to control. In a sense, you'll be designing an interpreter for that process. pexpect is a toolset for Python based on this idea.

like image 168
André Caron Avatar answered Jan 27 '26 17:01

André Caron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!