Redirecting stderr for extension modules

Michael Pyle mpyle at legato.com
Thu May 15 12:15:31 EDT 2003


An update and a little enlightment. It appears that modifications made to a
variable made inside of a finally clause are not retained outside of the
clause? When I move the flush, seek and read to just below the fn()
execution call, the stderr text appears in my stderr. Or at least it does on
Solaris. On Windows the text never actually makes it into the stderr.txt
file to begin with.
 
--Mike

-----Original Message-----
From: Michael Pyle [mailto:mpyle at legato.com] 
Sent: Thursday, May 15, 2003 8:45 AM
To: 'python-list at python.org'
Subject: Redirecting stderr for extension modules



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.

Here's what I have: 

def Redirect( fn, *args, **kwds ): 
    """ 
    Redirect( fn, ... ) -> (fn return value, stderr) 
    
    Captures any text written to stderr from the execution of fn. fn 
    is expected to be an extension module function. 
    """ 
    fd = os.dup( 2 ) 
    if fd != -1: 
        try: 
            file = open( 'stderr.txt', 'w+' ) 
            os.dup2( file.fileno(), 2 ) 
        except: 
            file = None 
        
    stderr = None 
    try: 
        result = fn( *args, **kwds ) 
        return result, stderr 
    finally: 
        if file: 
            file.flush() 
            file.seek( 0, 0 ) 
            stderr = file.read() 
            file.close() 
        
        if fd != -1: 
            os.dup2( fd, 2 ) 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20030515/9b4b68fb/attachment.html>


More information about the Python-list mailing list