Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cross platform /dev/null in Python

Tags:

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.

like image 602
Tristan Avatar asked May 28 '10 14:05

Tristan


People also ask

Can you read from Dev Null?

You write to /dev/null every time you use it in a command such as touch file 2> /dev/null. You read from /dev/null every time you empty an existing file using a command such as cat /dev/null > bigfile or just > bigfile. Because of the file's nature, you can't change it in any way; you can only use it.

What is a null device used for?

The null device is typically used for disposing of unwanted output streams of a process, or as a convenient empty file for input streams. This is usually done by redirection. The /dev/null device is a special file, not a directory, so one cannot move a whole file or directory into it with the Unix mv command.

What happens when you write data to Dev Null?

Whatever you write to /dev/null will be discarded, forgotten into the void. It's known as the null device in a UNIX system.


2 Answers

How about os.devnull ?

import os f = open(os.devnull,"w") zookeeper.set_log_stream(f) 
like image 53
msanders Avatar answered Sep 24 '22 14:09

msanders


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.

like image 21
Alex Martelli Avatar answered Sep 21 '22 14:09

Alex Martelli