get text from rogramms runn by subprocess.Popen immediatetly

grocery_stocker cdalten at gmail.com
Thu Apr 16 15:24:27 EDT 2009


On Apr 16, 4:12 am, Rüdiger Ranft <_r... at web.de> wrote:
> Hi all,
>
> I need to call some programms and catch their stdout and stderr streams.
> While the Popen class from subprocess handles the call, I get the
> results of the programm not until the programm finishes. Since the
> output of the programm is used to generate a progress indicator, I need
> a way to acces the values written to stdout/stderr as fast as possible.
>
> Beneath is a test which shows what I did
>
> TIA
> Rudi
>
> ----8<-------8<-------8<-- iodummy.cpp -8<-------8<---
> #include <iostream>
> #include <unistd.h>
>
> int main()
> {
>         for( int i = 0; i < 10; i++ )
>         {
>                 std::cerr << i << std::endl;
>                 sleep(2);
>         }
>
> }
>
> from subprocess import Popen, PIPE
> from time import sleep
>
> p = Popen('./iodummy',stdin=PIPE, stdout=PIPE, stderr=PIPE)
> sleep(3)
> # now I expect '0\n1\n' in stderr, but read() blocks until
> # the end of iodummy.
> print p.stderr.read()
> p.wait()
>

I'm sure the regulars will correct me, but if are on some kind of *nix
variant, couldn't you just redirect the stderr to the stdout like the
following

[cdalten at localhost oakland]$ more nope2.py
#!/usr/bin/python

import os
os.popen('./iodummy 2>&1', 'w')
[cdalten at localhost oakland]$ ./nope2.py
0
1
2
3
4
5
6
7
8
9
[cdalten at localhost oakland]$



More information about the Python-list mailing list