subprocess -popen - reading stdout from child - hangs
Suresh Babu Kolla
kollasb+news at gmail.com
Sun Sep 23 01:57:58 EDT 2007
gregpinero at gmail.com wrote:
> Let's say I have this Python file called loop.py:
>
> import sys
> print 'hi'
> sys.stdout.flush()
> while 1:
> pass
>
> And I want to call it from another Python process and read the value
> 'hi'. How would I do it?
>
> So far I have tried this:
>
>>>> proc = subprocess.Popen('python /home/chiefinnovator/loop.py',shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE)
>>>> proc.stdout.read()
>
From python documentation
`read([size])'
Read at most SIZE bytes from the file (less if the read hits `EOF'
before obtaining SIZE bytes). If the SIZE argument is negative or
omitted, read all data until `EOF' is reached. The bytes are
returned as a string object. An empty string is returned when
`EOF' is encountered immediately. (For certain files, like ttys,
it makes sense to continue reading after an `EOF' is hit.) Note
that this method may call the underlying C function `fread()' more
than once in an effort to acquire as close to SIZE bytes as
possible. Also note that when in non-blocking mode, less data than
what was requested may be returned, even if no SIZE parameter was
given.
read call in your code is waiting for EOF, since the script never exits
EOF is not reached.
Change read code to
proc.stdout.readline()
or
remove while 1 loop from loop.py.
HTH
Kolla
More information about the Python-list
mailing list