0

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 Answer 1

1

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).

Sign up to request clarification or add additional context in comments.

1 Comment

I tried running this code by replacing the ` # acquire threading lock` comment with print(msg), but the code never terminates - it just keeps running. I've also tried appending msg to a list, and the same result occurs.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.