Reading Live Output from a Subprocess

Vinay Sajip vinay_sajip at yahoo.co.uk
Fri Apr 6 16:14:40 EDT 2012


On Apr 6, 7:57 am, buns... at gmail.com wrote:

> I've heard that the Pexpect module works wonders, but the problem is that relies on pty which is available in Unix only. Additionally, because I want this script to be usable by others, any solution should be in the standard library, which means I'd have to copy the Pexpect code into my script to use it.
>
> Is there any such solution in the Python 3 Standard Library, and if not, how much of a thorn is this?
>
> "There should be one-- and preferably only one --obvious way to do it."
> Unfortunately, this is one case where the above is true for Perl but not Python. Such an example in Perl is
>
> open(PROG, "command |") or die "Couldn't start prog!";
>         while (<PROG>) {
>                  print "$_"; }
>
> (Note that I do not know Perl and do not have any intentions to learn it; the above comes from the script I was previously copying and extending, but I imagine (due to its simplicity) that it's a common Perl idiom. Note however, that the above does fail if the program re-prints output to the same line, as many long-running C programs do. Preferably this would also be caught in a Python solution.)
>
> If there is a general consensus that this is a problem for lots of people, I might consider writing a PEP.
>
> Of course, my highest priority is solving the blasted problem, which is holding up my script at the moment. (I can work around this by redirecting the program to a tmp file and reading that, but that would be such a perilous and ugly kludge that I would like to avoid it if at all possible.)


Try the sarge package [1], with documentation at [2] and source code
at [3]. It's intended for your use case, works with both Python 2.x
and 3.x, and is tested on Linux, OS X and Windows. Disclosure: I'm the
maintainer.

Regards,

Vinay Sajip

[1] http://pypi.python.org/pypi/sarge/0.1
[2] http://sarge.readthedocs.org/en/latest/
[3] https://bitbucket.org/vinay.sajip/sarge/



More information about the Python-list mailing list