8

I am writing a script which has 5 threads, i want to share/redirect stdout for all the thread, to get all prints properly. I have tried with the below code but its not working, can anybody help?

class Logwriter():
    def __init__(self):
        self.terminal = sys.stdout

    def write(self,message):
        lock = threading.Lock()
        lock.acquire()
        self.terminal.write(message)
        lock.release()

sys.stdout=Logwriter()

2 Answers 2

12

Instead of redirecting stdout (which won't provide redirection of stderr btw), you could also use the python logging module.

Then you can replace your print statements with logging.info("message").

The logging module provides a lot of possibilities like printing which thread posted a message etc.

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

Comments

2

Instantiate a lock in the __init__ method and use it with a with statement in the write method:

class Logwriter():
    def __init__(self):
        self.terminal = sys.stdout
        self.lock = threading.Lock()

    def write(self,message):
        with self.lock:
            self.terminal.write(message)

Also, this won't work because print "hello" calls sys.stdout.write("hello") first, then sys.stdout.write("\n").

You'll find a similar implementation that handles that issue in this answer by Alex Martelli.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.