在Python中跨平台/ dev / null

我使用下面的代码来隐藏在Linux / OSX上的Python库stderr我不控制默认情况下写入stderr:

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

是否有一个简单的跨平台替代/ dev / null? 理想情况下,它不会消耗内存,因为这是一个漫长的过程。

如何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()) 

当然,打开os.devnull也不错,但是这样每个输出操作都会发生(作为noop)“进程中” – 没有上下文切换到操作系统并返回,也没有缓冲(一些缓冲通常由open ),从而更less的内存消耗。

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

创build你自己的文件类的对象,不做任何事情?

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

廉价解决scheme警告

 class DevNull(): def __init__(self, *args): self.closed = False self.mode = "w" self.name = "<null>" self.encoding = None self.errors = None self.newlines = None self.softspace = 0 def close(self): self.closed == True @open_files_only def flush(self): pass @open_files_only def next(self): raise IOError("Invalid operation") @open_files_only def read(size = 0): raise IOError("Invalid operation") @open_files_only def readline(self): raise IOError("Invalid operation") @open_files_only def readlines(self): raise IOError("Invalid operation") @open_files_only def xreadlines(self): raise IOError("Invalid operation") @open_files_only def seek(self): raise IOError("Invalid operation") @open_files_only def tell(self): return 0 @open_files_only def truncate(self): pass @open_files_only def write(self): pass @open_files_only def writelines(self): pass def open_files_only(fun): def wrapper(self, *args): if self.closed: raise IOError("File is closed") else: fun(self, *args) return wrapper