How to depress the output of an external module ?

Carl Banks pavlovevidence at gmail.com
Tue Dec 26 19:42:10 EST 2006


Carl Banks wrote:
> fdu.xiaojf at gmail.com wrote:
> > After some trials I found that put "os.close(1)" before calling the
> > function will depress the output. In fact, "os.close(1)" closed
> > standard output, but I don't know how to open it again after the function's
> > execution.
>
> Try this:
>
> fd = os.dup(1)
> os.close(1)
> sys.stdout = os.fdopen(fd)

Also, right after closing file descriptor 1, you might want to set it
to something so as to eliminate an annoying warning message when Python
tries to close it upon termination but finds it already closed.  This
opens /dev/null and puts it in file descriptor 1 if not there already
(the fdz != 1 test might be unnecessary; I don't know if all flavors of
Unix always use the lowest available file descriptor).

fdz = os.open("/dev/null",os.O_WRONLY)
if fdz != 1:
    os.dup2(fdz,1)
    os.close(fdz)


Carl Banks




More information about the Python-list mailing list