Redirect sys.stderr to method of class instance?

160 views Asked by At

In python, is it possible to redirect sys.stderr to the method of a class instance? Having tried and failed to use the standard logging module in conjunction with the multiprocessing module, I've resorted to writing my own, custom logger. While this may be a poor alternative, I only need basic logging capabilities and the endless serialization errors were driving me crazy. In short I'd like to do something like,

import sys
class TestClass():

    def test_method(msg):
        acquire threading lock and write to file

logger = TestClass()
sys.stderr = logger.test_method

Can this be done?

1

There are 1 answers

1
kindall On

Any file-like object can be used as stderr -- it doesn't even need to be derived from file and mainly just needs a write() method. Essentially, you just need to name your test_method as write and assign sys.stderr to logger rather than logger.test_method. You may also want to implement flush(), possibly doing nothing.

class TestClass():

    def write(msg):
        # acquire threading lock and write to file

    def flush():
        pass

logger = TestClass()
sys.stderr = logger

You could also implement __enter__ and __exit__ methods to make your class work as a context manager, especially if there is cleanup needed (e.g. restoring stderr to the usual file).