You can do the following:
def send(self,txt): self.pipe.tochild.write("%4d" % len(txt)) self.pipe.tochild.write(txt) self.pipe.tochild.flush() def recv(self): l = self.pipe.fromchild.read(4) lv = int(l) return self.pipe.fromchild.read(lv)
But I admit I'm not sure why your original code doesn't work. Must be something weird with the buffering of the pipe object.
OMG! You rock - I would not have even thought of doing that. I thought it was cat that was just sitting there doing nothing, I guess i never realized that it may have been the read()'s fault.
]]> def send(self,txt):
self.pipe.tochild.write("%4d" % len(txt))
self.pipe.tochild.write(txt)
self.pipe.tochild.flush()
def recv(self):
l = self.pipe.fromchild.read(4)
lv = int(l)
return self.pipe.fromchild.read(lv)
But I admit I'm not sure why your original code doesn't work. Must be something weird with the buffering of the pipe object.
]]>import popen2
import sys, os
class bgprocess:
def __init__(self,cmdline):
self.pipe = popen2.Popen4(cmdline)
def __del__(self):
self.pipe.fromchild.close()
self.pipe.tochild.close()
def send(self,txt):
self.pipe.tochild.write(txt)
self.pipe.tochild.flush()
def recv(self):
return self.pipe.fromchild.read()
b = bgprocess("cat")
b.send("hellon")
print "printing: " + b.recv()
If you run "cat" at the command line, it simple echos back what you type when you hit enter. I want to interface with this (as an example only).
However, the above hangs. If you were to replace the flush() call in bgprocess.send, with "close()" then everything works perfectly. Problem is, I just closed my stdin for the childprocess. If I wanted to repeatedly use this as a "command handler", it wouldn't work.
Does anyone know away around this? It seems to work fine until the background proces is interactive.
]]>