First of all, your code should work if the child process is actually writing to its stdout. If there is an error in your command, the output might appear on stderr instead.
Note though that your code does not exit the loop so you need to fix that up, e.g. by calling break
when you read an empty string.
But there is a better way. Instead of reading the child process' stdout directly, Use Popen.communicate()
:
from subprocess import Popen, PIPE
connection_string = "yowsup-cli demos --yowsup --config config"
popen_parameters = connection_string.split(" ")
proc = Popen(popen_parameters, stdout=PIPE, stderr=PIPE)
out, err = proc.communicate()
if out:
print "Received stdout output of length {} from child process".format(len(out))
print out
elif err:
print "Received stderr output of length {} from child process".format(len(err))
print err
The other part of your question deals with interacting with the child process. In the simple case that you start the child process and send it a single input you can still use Popen.communicate()
by passing a string argument to it. Note that you need to setup the stdin pipe too. So, as above but:
proc = Popen(popen_parameters, stdin=PIPE, stdout=PIPE, stderr=PIPE)
data = 'data to send to child'
out, err = proc.communicate(data)
If your interaction with the child is more complex, you should consider using the pexpect
module which is designed for this usage. While it is possible to do it with Popen()
there are some issues with buffering and deadlocking of processes reading/writing pipes, so that is best avoided.