Subprocess with a Python Session?

Hendrik van Rooyen mail at microcorp.co.za
Thu Dec 7 23:54:40 EST 2006


"Giovanni Bajo" <noway at ask.me>

> Fredrik Lundh wrote:
>
> >> No matter what I do I cant get the following code to do what I expect.
> >> I hadn't used subprocess t o read and write to pipes of a
> >> still-running app, and I just can't seem to get it right. What gives?
> >>
> >> import subprocess
> >>
> >> p = subprocess.Popen("python", stdout=subprocess.PIPE,
> >> stdin=subprocess.PIPE)
> >> p.stdin.write('print 10\n')
> >
> > + p.stdin.close()
> >
> >> assert p.stdout.readline() == '10\n'
>
> Yeah, but WHY was the API designed like this? Why can't I read and write
> freely from a pipe connected to a process as many times as I want?

you can - all you have to do is to somehow separate the "records" - else how is
the receiving side to know that there is not more data to follow?

The simplest way is to use newline as separator, and to use readline() on the
receiving side.
Or you can use read(1) and roll your own...

To make sure the stuff is written from memory on the transmitting side, use
flush(), if you want to do many records, or close() as Fredrik said if only one
thing is to be transferred.

- Hendrik




More information about the Python-list mailing list