How to split stdout for multi-threaded python script?

I am writing a script that has 5 threads, I want to split / redirect stdout for the whole thread to get all prints correctly. I tried with the code below, but its not working, can anyone 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()
+4
source share
2 answers

Instead of redirecting stdout (which stderr btw will not redirect), you can also use the python logging module .

You can then replace your print statements with logging.info (the "message").

The logging module provides many features, such as printing, in which the stream sent a message, etc.

+5
source

__init__ with write:

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

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

, , print "hello" sys.stdout.write("hello"), sys.stdout.write("\n").

, Alex Martelli.

+1

All Articles