python : print output of each thread to seperate file

一世执手 提交于 2020-01-30 08:18:05

问题


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

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/19470682/python-print-output-of-each-thread-to-seperate-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!