Get Stdout from external script startet through python

Donn Cave donn at drizzle.com
Mon Nov 18 00:08:31 EST 2002


Quoth Pearu Peterson <pearu at cens.ioc.ee>:
...
| But may I extend the question to extension modules, that is, how to get
| the (stdout or stderr) output that originates, say, from a
| fprintf(stdout, ...) statement in an Python/C extension module?
|
| This questions has been raised also in f2py-users mailing list where
| there was a wish to catch the stdout of a Fortran subroutine, wrapped to
| Python. So far I have only an idea that this could be achieved
| 1) by determining the pty (with os.ttyname(sys.stdout.fileno())) where
| these messages go;
| 2) and then using socket and termios modules to get the Fortran or C
| messages.

Ouch.  You may be pleased to learn that it is not nearly such a hard
problem (or perhaps disappointed to find that it's worse than that.)

The basic question is, ``how can I read my own output?''  The obvious
answer is, redirect it to storage - a disk file, or a pipe if you're
absolutely certain the output gathered in one write session will be
small enough to fit in the pipe (in other words, don't use a pipe.)
Your UNIX operating system provides the means to do this redirection.

1.  fd = posix.open(tmpfile, posix.O_WRONLY|posix.O_CREAT)
2.  save_fd = posix.dup(1)

3.  sys.stdout.flush()
4.  posix.dup2(fd, 1)
    ... call functions, saving output
5.  sys.stdout.flush()
6.  posix.dup2(save_fd, 1)
    ... now output is back to normal
... repeat from (3) as required.

So this redirection applies indiscrimately to your entire process,
whether it's Python code or whatever.

	Donn Cave, donn at drizzle.com



More information about the Python-list mailing list