0

I have a linux application that runs interactively from commandline using stdin to accept commands. I've written a wrapper using subprocess to access stdin while the application is backgrounded. I can now send commands to it using p.stdin.write(command) but how do I go about monitoring its responses?

dpcd
  • 1
  • 1
  • 1
    Looks like a relevant link: http://stackoverflow.com/questions/375427/non-blocking-read-on-a-stream-in-python – pyfunc Oct 06 '10 at 06:11

1 Answers1

1

Read from p.stdout to access the output of the process.

Depending on what the process does, you may have to be careful to ensure that you do not block on p.stdout while p is in turn blocking on its stdin. If you know for certain that it will output a line every time you write to it, you can simply alternate in a loop like this:

while still_going:
    p.stdin.write('blah\n')
    print p.stdout.readline()

However, if the output is more sporadic, you might want to look into the select module to alternate between reading and writing in a more flexible fashion.

Josh Lee
  • 171,072
  • 38
  • 269
  • 275
  • I'm having some trouble understanding how to use select. do you know of any examples that would be relevant to my situation? – dpcd Oct 06 '10 at 06:31
  • @dpcd There are several different ways to use select and it depends on how your code is structured as to which way is best. The two main patterns are "block until any one of these files becomes writeable... then tell me which ones are" and "Don't block, just tell me if data is available. That way I don't accidentally block my process by calling read() on a file that doesn't have data ready" – Rakis Oct 06 '10 at 12:55
  • @dpcd Oh, and Python's `select()` is a very thin wrapper over the standard POSIX `select()`. All the C-based examples you'll find while googling select apply pretty much the same to python as to C (python just returns lists instead of bitmaps). There are plenty of examples & tutorials out there. – Rakis Oct 06 '10 at 12:57