ATOzTOA ATOzTOA - 1 month ago 16
Python Question

Redirect stdout to a file only for a specific thread

I have couple of processes with its own threads all writing to

stdout
and I am OK with it. Now, I have to add another thread, which is going to dump a lot of garbage to stdout and I don't want this.

Is there any way I can redirect the
stdout
for a single thread to a file?

Update

As mentioned by owobeid, I tried this... I am redirecting
stderr
to a file...

def startServer():
fd = os.open("foo.txt", os.O_RDWR|os.O_CREAT )
fd2 = 2
os.dup2(fd, fd2)

# rest of the code

if __name__ == '__main__':
threading.Thread(target=startServer).start()
raise Exception("My Exception")


Issue:
stderr
for the whole app is redirected. The Exception message also gets redirected into the file, even though it is outside the thread.

Answer

Use dup2 to redirect the output to a file of your choice. Set fd to your file descriptor and fd2 to 1 (stdout).

Note: Do this inside the spawned thread, not in the main thread.