Cross platform /dev/null in Python

Question:

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.

Asked By: Tristan

||

Answers:

How about os.devnull ?

import os
f = open(os.devnull,"w")
zookeeper.set_log_stream(f)
Answered By: msanders
>>> import os
>>> os.devnull
'nul'
Answered By: SilentGhost
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.

Answered By: Alex Martelli

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
Answered By: Andrew Aylett

Cheap solution warning!

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
Answered By: badp
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.