script = """
print "Something to print"
while(True):
r=raw_input()
if r=='n':
print "Exiting"
break
else :
print "not time to break"
"""
from subprocess import PIPE, Popen
p = Popen( [ "python" , "-u" , "-c" , script] , stdin= PIPE, stdout= PIPE, bufsize= 1 )
print p.stdout .readline ( ) , # read the first line
for i in range ( 10 ) : # repeat several times to show that it works
print >> p.stdin , i # write input
print p.stdout .readline ( ) , # read output
print p.communicate ( "n\n " ) [ 0 ] , # signal the child to exit,
# read the rest of the output,
# wait for the child to exit
c2NyaXB0ID0gIiIiCnByaW50ICJTb21ldGhpbmcgdG8gcHJpbnQiCndoaWxlKFRydWUpOgogIHI9cmF3X2lucHV0KCkKICBpZiByPT0nbic6CiAgICBwcmludCAiRXhpdGluZyIKICAgIGJyZWFrCiAgZWxzZSA6CiAgICBwcmludCAibm90IHRpbWUgdG8gYnJlYWsiCiIiIgpmcm9tIHN1YnByb2Nlc3MgaW1wb3J0IFBJUEUsIFBvcGVuCgpwID0gUG9wZW4oWyJweXRob24iLCAiLXUiLCAiLWMiLCBzY3JpcHRdLCBzdGRpbj1QSVBFLCBzdGRvdXQ9UElQRSwgYnVmc2l6ZT0xKQpwcmludCBwLnN0ZG91dC5yZWFkbGluZSgpLCAjIHJlYWQgdGhlIGZpcnN0IGxpbmUKZm9yIGkgaW4gcmFuZ2UoMTApOiAjIHJlcGVhdCBzZXZlcmFsIHRpbWVzIHRvIHNob3cgdGhhdCBpdCB3b3JrcwogICAgcHJpbnQgPj5wLnN0ZGluLCBpICMgd3JpdGUgaW5wdXQKICAgIHByaW50IHAuc3Rkb3V0LnJlYWRsaW5lKCksICMgcmVhZCBvdXRwdXQKCnByaW50IHAuY29tbXVuaWNhdGUoIm5cbiIpWzBdLCAjIHNpZ25hbCB0aGUgY2hpbGQgdG8gZXhpdCwKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICMgcmVhZCB0aGUgcmVzdCBvZiB0aGUgb3V0cHV0LCAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICMgd2FpdCBmb3IgdGhlIGNoaWxkIHRvIGV4aXQKCg==