简体   繁体   中英

python : print output of each thread to seperate file

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()

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM