Interprocess comunication

Oscar Benjamin oscar.benjamin at bristol.ac.uk
Thu Jun 7 12:25:20 EDT 2012


On 7 June 2012 17:04, Julio Sergio <juliosergio at gmail.com> wrote:

> I'm trying to call an external process to filter some of my data, i.e., I'm
> trying to pass some information to the called process, and have this
> information
> back transformed. I started testing with the linux 'cat' command, in this
> way:
>
>
> ->>> import subprocess as sp
> ->>> p = sp.Popen(["cat"],stdin=sp.PIPE,stdout=sp.PIPE,close_fds=True)
> ->>> (fi,fo) = (p.stdin, p.stdout)
> ->>> fi.write("SOMETHING\n")
> ->>> fi.flush()
> ->>> fo.readline()
> 'SOMETHING\n'
> ->>> fi.write("OTHER\n")
> ->>> fi.flush()
> ->>> fo.readline()
> 'OTHER\n'
> ->>> fi.write("NEXT\n")
> ->>> fi.flush()
> ->>> fo.readline()
> 'NEXT\n'
> ->>> fi.write("NEXT1\n")
> ->>> fi.flush()
> ->>> s = fo.readline()
> ->>> s
> 'NEXT1\n'
>
> Up to this point it worked as expected. However, when I tryied with the
> methods
> that write and read several lines, apparently the process got stalled:
>
> ->>> fi.writelines(["uno\n","dos\n","tres\n"])
>
->>> fi.flush()
>
->>> s = fo.readlines()
>

The readlines() method is intended to read an entire file and split it into
lines, so it blocks until EOF is found. If you want to use readlines(), you
should first close the subprocesses stdin:

>>> fi.writelines(["uno\n","dos\n","tres\n"])
>>> fi.flush()
>>> fi.close()
>>> s = fo.readlines()

Although now you can no longer use the subprocess for reading or writing.
If that is not what you want in your actual problem then you'll need to
avoid readlines().


> .
> .
> .
>
> Do you have any comments on this?
>
> Thanks,
>
>  --Sergio
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20120607/f4b15150/attachment.html>


More information about the Python-list mailing list