python日志与多处理,根日志不同于windows

2024-05-19 23:25:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试了用多处理进行日志记录,发现在windows下,我会在子进程中使用不同的根日志记录程序,但在Linux下这没问题。在

测试代码:

在主.py公司名称:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import multiprocessing
from mymod import func

def m_func():
    server = multiprocessing.Process(target=func, args=())
    server.start()

logger = logging.getLogger()
#print 'in global main: ', logger

if __name__ == '__main__':
    print 'in main: ', logger
    m_func()

在mymod.py公司公司名称:

^{pr2}$

在Linux下,结果是:

in main:  <logging.RootLogger object at 0x10e4d6d90>
in func:  <logging.RootLogger object at 0x10e4d6d90>

但在64位Windows 7下,我将在main和func之间获取不同的根记录器:

in main:  <logging.RootLogger object at 0x00000000021FFD68>
in func:  <logging.RootLogger object at 0x00000000023BC898>

如果我在主脚本中初始化根记录程序,如何在windows下保持子进程中的级别等设置?在


Tags: inimport程序object进程mainlinuxwindows
1条回答
网友
1楼 · 发布于 2024-05-19 23:25:47

在我看来,这可能与the following platform-dependant behaviour有关:

16.6.3.2. Windows Since Windows lacks os.fork() it has a few extra restrictions:

(...)

Global variables

Bear in mind that if code run in a child process tries to access a global variable, then the value it sees (if any) may not be the same as the value in the parent process at the time that Process.start was called.

However, global variables which are just module level constants cause no problems.

根据您的问题,我假设这会导致一个logging.basicConfig()调用,该调用没有到达所有进程。解决方法是让您的子进程记录到Queue(使用QueueHandler),并在主进程中有一个专用线程来监听队列。在

相关问题 更多 >