Thursday, November 6, 2008

Using pipes with python.

This lists a bit of code I developed to use pipes with python
import os
import sys

def function():
r1,w1 = os.pipe()
r2,w2 = os.pipe()
if (os.fork() == 0):
# we're the child
os.close(1)
os.dup2(w2,1)
os.close(0)
os.dup2(r1,0)
sys.stdin = os.fdopen(0)
sys.stdout = os.fdopen(1,'w')
os.execl("/bin/bash")
else:
# we're the parent
to_child = os.fdopen(w1,'w')
from_child = os.fdopen(r2)
to_child.write("ls\n")
to_child.flush()
to_child.write("echo hi\n")
to_child.flush()
temp = from_child.readline()
while temp:
print temp
temp = from_child.readline()

function()
The only problem with this code at the moment is, I don't know how to get readline() to return when there's nothing to read. In short, we always end up hanging!

A much simpler way to achieve the effect of the above would be to use the popen3 function.
>>> import os
>>> i,o,u = os.popen3("/bin/bash")
>>> i.write ("ls\n")
>>> i.flush()
>>> o.readline()
'bin\n'
>>> o.readline()
'Desktop\n'
>>> o.readline()
'Documents\n'
>>> o.readline()
'mounting-vmdk.pdf\n'
>>> o.readline()
'order-cardbus-to-express.pdf\n'
>>> o.readline()
'public_html\n'
>>> o.readline()
'vmware\n'
>>> o.readline()
# at this point, again we hung !!
The problem with readline hanging still exists, but the code's much simpler

.

No comments: