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()
Chirag Gangdev
  • 137
  • 2
  • 2
  • 6

2 Answers2

10

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.

Felix
  • 6,131
  • 4
  • 24
  • 44
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.

Community
  • 1
  • 1
Vincent
  • 12,919
  • 1
  • 42
  • 64