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?

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.