小编Mat*_*ier的帖子

Python 3:使用多处理队列进行日志记录

最近,我面临着在我们的软件中进行多处理的挑战。我想要一个主进程来生成子进程,并且我需要某种方法将日志信息发送回主进程。这主要是因为我们使用的模块将警告和错误消息写入日志对象,并且我们希望这些消息出现在主进程中运行的 GUI 中。

显而易见的方法是编写一个带有 write() 方法的小类,该方法将 put() 放入队列,然后在日志流处理程序中使用此类。然后主进程将从该队列中 get() 将文本发送到 gui。但这似乎不起作用,我不知道为什么

我编写了一些示例代码来演示该问题。它使用日志对象在子进程中写入队列,然后主进程尝试从队列中读取,但失败。有人可以帮我弄清楚这有什么问题吗?

import time, multiprocessing, queue, logging

class FileLikeQueue:
    """A file-like object that writes to a queue"""
    def __init__(self, q):
        self.q = q
    def write(self, t):
        self.q.put(t)
    def flush(self):
        pass


def func(q):
    """This function just writes the time every second for five 
    seconds and then returns. The time is sent to the queue and 
    to a logging object"""

    stream = FileLikeQueue(q)

    log = logging.getLogger()
    infohandler = logging.StreamHandler(stream)
    infohandler.setLevel(logging.INFO)
    infoformatter = …
Run Code Online (Sandbox Code Playgroud)

python queue logging multiprocessing python-3.x

5
推荐指数
1
解决办法
3247
查看次数

标签 统计

logging ×1

multiprocessing ×1

python ×1

python-3.x ×1

queue ×1