pipe in read and write mode

Alex Martelli aleaxit at yahoo.com
Mon Jul 16 07:56:43 EDT 2001


"Raphael Bauduin" <rb at tiscali.be> wrote in message
news:newscache$d58kgg$wzn$1 at news.freegates.be...
> Hi!
>
> I want to pipe the standard input of my script to a command. I use popen,
> and it's fine. However, I want to take the standard output of the command
> and put it in a variable. I can't open the pipe in read and write mode. I
> made it work by redirecting the output of the pipe to a file, and reading
> this file. I would prefer not to write it to a temporary file, as the text
> piped is somewhat sensitive (I use the script to encrypt it, so it would
be
> better not to write it to a file ;-)

Function popen2 in module os returns a pair, a tuple with two items:
the first item is the child process's standard-input, the second one,
the child process's standard-output.  So, yes, you CAN open pipes in
both read and write modes!

Here's a self-contained Python toy example.  Say we have this
decorate.py script...:
import fileinput
for line in fileinput.input():
    print fileinput.lineno(),'->',line,

Here's how we can control both its input and its output with
an os.popen2 call:

D:\py21>python
Python 2.1.1c1 (#19, Jul 13 2001, 00:25:06) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
Alternative ReadLine 1.4 -- Copyright 2001, Chris Gonnerman
>>> import os
>>> fi, fo = os.popen2('python decorate.py')
>>> fi.writelines('uno\ndue\ntre\necc ecc\n'.splitlines(1))
>>> fi.close()
>>> x=fo.readlines()
>>> x
['1 -> uno\n', '2 -> due\n', '3 -> tre\n', '4 -> ecc ecc\n']
>>>


Alex






More information about the Python-list mailing list