2012-02-03 62 views

回答

7

你可以簡單地用定製類文件對象代替sys.stdoutsys.stderr

import sys 

sys.stdout = open('stdout.log', 'a') 
sys.stderr = open('stderr.log', 'a') 

要撤消:

sys.stdout = sys.__stdout__ 
sys.stderr = sys.__stderr__ 

欲瞭解更多信息,請閱讀sys module documentation

1
import sys 


class OutDevice(): 
    def write(self, s): 
     # do whatever 
     pass 

class ErrDevice(): 
    def write(self, s): 
     # do whatever 
     pass 

sys.stdout = OutDevice() 
sys.stdout = ErrDevice() 

# to restore 
sys.stdout = sys.__stdout__ 
sys.stderr = sys.__stderr__ 
相關問題