开发者

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

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.


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.


Have a look at pexpect.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜