redirecting stdio for extension function

Michael Schmitt nomail at nomail.com
Thu Oct 16 13:02:31 EDT 2003


>> I am using an extension function (written in C), which produces a lot of
>> output via fprintf statements.
>> Is there a way to redirect this output, without changing the extension
>> function?
> 
> You can muck with the file descriptors 0, 1 and 2 at a pretty low
> level if you're on Unix:

Thanks for the hint.
I tried the following two functions:

fd_stdout= os.dup(1)
def outputOff():
    nsofd = os.dup(1)
    nso = os.fdopen(nsofd, 'w')
    sys.stdout = nso
    dnfd = os.open('/dev/null', os.O_WRONLY)
    os.close(1)
    os.dup2(dnfd, 1)
    os.close(dnfd)

def outputOn():
    os.close(1)
    os.dup2(fd_stdout, 1)

But calling outputOn() seems to write the previously redirected output to 
the screen again. So it seems to be buffered.
I played a bit with ftruncate, but have no idea yet, how to discard the 
buffered output.

Thanks.

Michael




More information about the Python-list mailing list