1

I have several threads and each thread writes output to stdout. However I want to redirect the ouput of each thread to a separate file independently of each other.

What I mean is the following:

  • Thread1 writes every print, every exception and every other ouput into file1.log
  • Thread2 writes every print, every exception and every other ouput into file2.log
  • and so on.

So what I'm looking for is to set the stdout for each thread exclusivly. However setting the stdout only works globally mean that Thread1 and Tread2 will always write to the same defined stdout. I have not found out yet how to do this. The python logging is inapproriate for this as I've already checked this.

How can I do that?

EDIT: Based on the answer of dbra I wrote the following small program that demonstrate the logging:

#!/usr/bin/python
# -*- coding: utf-8 -*-

from multiprocessing import Process
import sys

class SubRunner(object):

    def print_something( self, name ):
        print name + ": print something"


class MainRunner(object):

    def __init__(self, name):        
        self.sub_runner = SubRunner()
        self.name = name


    def runme(self,dummy):
        sys.stdout = open('example_' + self.name + ".log", "w")
        self.sub_runner.print_something( self.name )


#Main program
m1 = MainRunner("M1")
m2 = MainRunner("M2")

p1 = Process(target=m1.runme, args=('',) )
p2 = Process(target=m2.runme, args=('',) )

p1.start()
p2.start()

p1.join()
p2.join()
toom
  • 12,864
  • 27
  • 89
  • 128

2 Answers2

2

Threads shares the same file descriptor table, you cannot redirect stdout to different files.

It would instead work by using multiprocessing instead of threading library, here an example of different file for different pid.

Community
  • 1
  • 1
dbra
  • 621
  • 3
  • 11
  • Actually, this is possible - [Redirect stdout to a file only for a specific thread](https://stackoverflow.com/a/43667367/5767241) – idanp Jun 06 '23 at 16:38
0

You created a process instead of a thread, which share no memory space. So you can simply set sys.stdout in subprocess, which will never influence other subprocesses or main process.

Given92
  • 101
  • 2
  • 8