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?
Any file-like object can be used as
stderr-- it doesn't even need to be derived fromfileand mainly just needs awrite()method. Essentially, you just need to name yourtest_methodaswriteand assignsys.stderrtologgerrather thanlogger.test_method. You may also want to implementflush(), possibly doing nothing.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. restoringstderrto the usual file).