Redirect stderr

Gordon McMillan gmcm at hypernet.com
Mon Aug 9 23:46:07 EDT 1999


David N. Welton wrote:

> I wish to do this:
> 
> #!/usr/bin/python
> 
> import sys
> import os
> 
> f = open("goober", "w")
> 
> sys.stderr = f
> sys.__stderr__ = f
> 
> os.execv("/bin/ls", ["/bin/ls", "sdfsdfdsfds"])
> 
> and have it dump the errors into 'goober'.  I'm having some
> difficulties figuring out exactly why this isn't working, or how I
> ought to be doing this.

Because sys.stderr is a Python file object, which (by default) uses 
C's stderr. Reassigning it doesn't change C's assignment. If you want 
to twiddle file descriptor 2, you can do it with os.close(2) etc. Or 
be lazy and just redirect it on the command line to the subprocess.

- Gordon




More information about the Python-list mailing list