Cross platform /dev/null in Python

I'm using the following code to hide stderr on Linux/OSX for a Python library I do not control that writes to stderr by default:

f = open("/dev/null","w")
zookeeper.set_log_stream(f)

Is there an easy cross platform alternative to /dev/null? Ideally it would not consume memory since this is a long running process.


How about os.devnull ?

import os
f = open(os.devnull,"w")
zookeeper.set_log_stream(f)

class Devnull(object):
    def write(self, *_): pass

zookeeper.set_log_stream(Devnull())

Opening os.devnull is fine too of course, but this way every output operation occurs (as a noop) "in process" -- no context switch to the OS and back, and also no buffering (while some buffering is normally used by an open) and thus even less memory consumption.


>>> import os
>>> os.devnull
'nul'

Create your own file-like object which doesn't do anything?

class FakeSink(object):
    def write(self, *args):
        pass
    def writelines(self, *args):
        pass
    def close(self, *args):
        pass