richo
richo

Reputation: 8999

Most pythonic way for a class to ignore output to stderr

I've got a class which uses the context management protocol to have a silent stderr stream for a while (mainly used for py2exe deployments, where the app writing anything to stderr causes ugly dialogs when the app is closed, and I'm doing something that I know will have some stderr output)

import sys
import os
from contextlib import contextmanager

@contextmanager
def noStderr():
    stderr = sys.stderr
    sys.stderr = open(os.devnull, "w")
    yield
    sys.stderr = stderr

My question is what would be more pythonic, the reasonably clean solution of opening the system's bit bucket and writing to that, or skipping allocation of the fd and write operations, and creating a new class ala:

class nullWriter(object):
    def write(self, string):
        pass

and then replacing the above code with

from contextlib import contextmanager

@contextmanager
def noStderr():
    stderr = sys.stderr
    sys.stderr = nullWriter()
    yield
    sys.stderr = stderr

Upvotes: 2

Views: 241

Answers (5)

richo
richo

Reputation: 8999

Thanks all for the replies.

I think I will go with the nullWriter approach. I'm aware that both options work, but more interested to see what seems cleaner (esp as the overhead of opening the file is negligable).

Upvotes: 0

prime_number
prime_number

Reputation: 758

What's wrong with that?

import sys

sys.stderr = open('/dev/null', 'w')

Upvotes: 1

abyx
abyx

Reputation: 72848

It's a decision between using things that already exist (os.devnull) but are a bit "messier" (you need to open() it etc'), and creating your own solution, which might be simpler, but it's a new class that you're creating.

Though both are totally fine, I would have gone with the nullWriter, as it's cleaner and depends on pure python knowledge and doesn't mess with os things.

Upvotes: 2

user72539
user72539

Reputation: 56

I think the latter solution is the more elegant. You avoid going to the system environment, potentially wasting an fd. Why go out the operating system when it's not needed?

Upvotes: 4

Chirael
Chirael

Reputation: 3085

I feel that the nullWriter class would be more "Pythonic" because it uses the Python interfaces already in place (that you can assign sys.stderr to anything that has a write method), rather than having to go out to the system environment and write to the "bit bucket" as you put it :)

Upvotes: 3

Related Questions