views:

55

answers:

1

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?

+1  A: 

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.

jleedev
I'm having some trouble understanding how to use select. do you know of any examples that would be relevant to my situation?
dpcd
@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
Rakis