Really closing stdout (was: "fork and exit" needed?)

Mitja Trampus nun at example.com
Tue Nov 28 19:24:45 EST 2006


Nick Craig-Wood wrote:

>>> open STDOUT, '>/dev/null'; 
>>  sys.stdout = open(os.devnull, 'w') 
> $ ls -l /proc/32004/fd
> total 4
> lrwx------ 1 ncw ncw 64 Nov 28 09:55 0 -> /dev/pts/17
> lrwx------ 1 ncw ncw 64 Nov 28 09:55 1 -> /dev/pts/17
> lrwx------ 1 ncw ncw 64 Nov 28 09:55 2 -> /dev/pts/17
> l-wx------ 1 ncw ncw 64 Nov 28 09:55 3 -> /dev/null
> 
> I'm not sure how you do open stdout to /dev/null in python though!
> I suspect something like this...
>   import posix
>   posix.close(1)
>   posix.open("/dev/null", posix.O_WRONLY)

Yes, you're close enough... The explanations are here:
http://www.google.com/search?q=python%20close%20stdout,
I like this one in particular:
http://www.python.org/infogami-faq/library/why-doesn-t-closing-sys-stdout-stdin-stderr-really-close-it/

If you explicitly want to leave file descriptors 0-2 present 
(Do you gain anything by not closing them? If you know, do 
tell...), but pointing do /dev/null, you could do:

null = os.open(os.devnull,os.O_WRONLY)
os.dup2(null,0)
os.dup2(null,1)
os.dup2(null,2)
os.close(null)

Untested.

More info on file descriptors and python here:
http://docs.python.org/lib/os-fd-ops.html

Mitja



More information about the Python-list mailing list