Python:将打印输出(stdout)重定向到使用多处理的日志记录
我正在开发一个python类,它使用我们自己开发的一些其他类/模块 我们在每个模块中使用一些打印来向用户提示一些信息(日志也用于获取更详细的信息)。 问题是,当“主”类使用(子)模块时,打印可能会变得太多,并隐藏了基本主信息。在我当前的应用程序中,“master”是一种遗传算法,它使用一个多处理子类(用于运行案例),该子类还使用一些其他子类(用于运行非python代码、定义初始化数据等)。每个类打印与该类相关的信息,而我只想显示主控信息 然后我尝试将sys.stdout和sys.stderr重定向到日志记录。见下文我对简化示例的尝试 被调用的模块Python:将打印输出(stdout)重定向到使用多处理的日志记录,python,logging,stdout,python-multiprocessing,Python,Logging,Stdout,Python Multiprocessing,我正在开发一个python类,它使用我们自己开发的一些其他类/模块 我们在每个模块中使用一些打印来向用户提示一些信息(日志也用于获取更详细的信息)。 问题是,当“主”类使用(子)模块时,打印可能会变得太多,并隐藏了基本主信息。在我当前的应用程序中,“master”是一种遗传算法,它使用一个多处理子类(用于运行案例),该子类还使用一些其他子类(用于运行非python代码、定义初始化数据等)。每个类打印与该类相关的信息,而我只想显示主控信息 然后我尝试将sys.stdout和sys.stderr重定
from multiprocessing import Process
def send2disp(text) :
print(text)
return
def send2disp_mp(text) :
workers = [Process(target=send2disp,args=(text+str(pi),)) for pi in range(2)]
for ti in workers :
ti.start()
for ti in workers :
ti.join()
if __name__ == '__main__':
pass
主脚本
from test_print import send2disp,send2disp_mp #'test_print' is the module filename
import logging
import sys
if __name__ == '__main__':
send2disp('NoRedirection->OnStdout')
logging.basicConfig(filename='test.log',level=logging.DEBUG,filemode='w')
logging.info('OnLog')
fl = logging.getLoggerClass().root.handlers[0].stream
sys.stdout = fl
sys.stderr = fl
print('InScript->IsOnLog')
send2disp('SubModule->IsOnLog')
send2disp_mp('ShouldBeOnlog')
使用主脚本,我定义了一个日志文件,并将stdout/stderr重定向到它。然后调用子模块的两个函数:
- “send2disp”工作正常,打印输出进入日志
- “send2disp\u mp”,而是继续将打印输出发送到标准输出…唯一的区别是使用多处理,这应该是问题的根源李>
提前感谢。我认为系统重定向只适用于当前流程。您是否尝试在子进程内执行重定向?我无法用python 2.7和python 3.6重现此问题,除了
'NoRedirection->OnStdout'
之外的所有内容都在file@CorentinLimier:我正在使用python 3.3.5。您可以尝试:在较新版本的python上使用吗?或者在send2disp\u mp函数中移动sys重定向(或者使用decorator)@corentilimier:如果这可能很重要,它是一个winpython安装,我正在windows powershell中运行脚本。