ATOzTOA ATOzTOA - 1 year ago 93
Python Question

Redirect stdout to a file only for a specific thread

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

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
for a single thread to a file?


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

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

# rest of the code

if __name__ == '__main__':
raise Exception("My Exception")

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download