Redirecting stderr for extension modules

Michael Pyle mpyle at legato.com
Thu May 15 14:24:06 EDT 2003


Hi Dave,

Thanks for the suggestion, unfortunately this doesn't appear to work on
Windows. Nothing ever gets written to my redirection file. I'm seeing the
same results I got using the file object based approach (which appears to
work fine on Solaris -- not the code I originally posted, which has some
errors in it related to the finally clause, but the cleaned up version that
doesn't use finally): nothing makes it out to my redirection file and when I
restore stderr (using dup2) to its original value, the stderr text show up
on the command line.

Thanks for the suggestion though, definitely worth a shot.

--Mike

-----Original Message-----
From: Donn Cave [mailto:donn at u.washington.edu] 
Sent: Thursday, May 15, 2003 10:48 AM
To: python-list at python.org
Subject: Re: Redirecting stderr for extension modules


Quoth Michael Pyle <mpyle at legato.com>:
... [HTML version omitted]
| I've been trying to find a way to redirect the stderr output of a 
| function in a C extension module. What I'd like to create is a 
| function that can take a callable and capture any output to stderr 
| that results from the execution of that callable. It then returns the 
| result of the execution and the stderr text as a tuple. It seems like 
| this should be pretty straight forward, but after a day or so of 
| scratching my head I just can't seem to get it to work.

Your problem is that you create your redirection file as Python file object,
and then later rewind and read that file object, but as you know, the output
actually gets there by writing to unit 2.  The file object is not aware of
this data.

If it's important to you for some reason to use a file object anyway, you
could reopen it instead of just rewinding it.  But since this does not
appear to be the case, you may as well open it with os.open, and eventually
read with os.read.

    sys.stderr.flush()
    efd = os.open('stderr.txt', os.O_RDWR|os.O_CREAT|os.O_TRUNC)
    os.dup2(efd, 2)
    ...
    sz = os.lseek(efd, 0, 1)
    os.lseek(efd, 0, 0)
    stderr = os.read(efd, sz)
    os.close(efd)
    return result, stderr

	Donn Cave, donn at u.washington.edu
--------
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20030515/da40a4c0/attachment.html>


More information about the Python-list mailing list