execl() and inheritied streams

exarkun at divmod.com exarkun at divmod.com
Tue Sep 28 16:00:59 EDT 2004


On Tue, 28 Sep 2004 12:53:18 -0600, "\"Erik Johnson\" <ej <at at bag.python.org>wellkeeper" <"dot>com"@bag.python.org> wrote:
>Hi,
> 
>     I am trying to use Python to remap stdout and stderr to a log file for
> an exec()'ed program.
> The following code seems to work fine for the script itself, but my
> expectation was that the exec'ed program would inherit its STDIN and STDOUT
> and so would be printing to the log file also. Unfortunately, that is not
> the case: the print statements in the spawned process come back to the
> screen.  So... I'm a little puzzled and am not finding information on how to
> remap the file descriptors other than to set sys.stdin, sys.stdout,
> sys.stderr.
> 

  Replacing sys.stdout, sys.stderr, and sys.stdin only effects code which goes through the sys module to find those streams.  The new process you execl() is very unlikely to do this, since your instance of the sys module will be destroyed by the execl() call :)  Instead, you need to twiddle file descriptors:

    f = file('out.txt', 'a')
    os.dup2(f.fileno(), sys.stdout.fileno())
    os.dup2(f.fileno(), sys.stderr.fileno())

  Now 1 and 2 (stdout and stderr, respectively) refer to a different file object down in the file descriptor table, far away from your process.  These survive execl() and so can have an effect on the executed process.

  Jp



More information about the Python-list mailing list