2016-07-13 79 views
2

我想重定向所有输出,即使是从导入到文件的外部模块。如何将python日志记录输出重定向到文件而不是stdout?

sys.stdout = open('logfile', 'a') 

不会为外部文件所做的日志记录工作在stdout上回显。

我已经修改了外部模块的源代码,并且它们与python的“日志记录”模块深深地结合在一起,并依靠它来输出。

此外,我不想使用流操作符使用流重定向。

回答

0

试试这个:

sysstdout = sys.stdout 
log_file = open("your_log_file.txt","w") 
sys.stdout = log_file 
print("this will be written to message.log") 
sys.stdout = sysstdout 
log_file.close() 

或者,做正确的事,并使用Python's logging module正常。

+0

不,不重定向导入的外部模块。外部模块似乎以自己的方式做事。 –

0
import sys 

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

print('this should be working from anywhere') 
import logging 
logging.warn('this too') 

你看到外部模块打印到控制台reasson可能是他们使用stderr(这是为logging模块默认的输出处理程序)者。

相关问题