【问题标题】:How can I pass a child processes stdout with queue? Python如何通过队列传递子进程标准输出? Python
【发布时间】:2016-07-15 01:11:32
【问题描述】:

我有一个 Logger 类,具有以下内容:

class Logger():
    def __init__(self):
        self.terminal = sys.__stdout___
        self.log = open('logFile.log', 'w')
    def write(message):
        self.terminal.write(message)
        self.log.write(message)

具有以下内容的主要内容:

import Logger, sys
sys.stdout = Logger.Logger()
import File1
File1.aFunc()

在文件 1 中:

def execSubProc(target,queue):
    target(queue)

q = multiprocess.Queue()
proc = multiprocess.Process(target=execSubProc, args=(testFunc,q))
proc.start()
proc.join()

在文件 2 中:

def testFunc(queue)
#Some print statements
#I want to get these print statements in the queue for main process to read

好的,这就是我的结构。我想要做的是从运行 testFunc() 的子进程中获取标准输出并将其放入队列中。当程序返回主程序时,我想从队列中读取并将这些内容写入日志文件。

我不能只在文件 2 中再次执行 sys.stdout = Logger.Logger(),因为这只会覆盖电源日志文件。我该怎么做才能捕获所有子进程标准输出并放入队列?

【问题讨论】:

    标签: python logging multiprocessing stdout


    【解决方案1】:

    一种解决方案是使用logging 模块。
    multiprocessing.util 中有一个记录器,可用于生成线程安全日志:

    import time
    import logging
    import multiprocessing as mp
    import multiprocessing.util as util
    from sys import stdout as out
    
    
    def runner(ids):
        log = util.get_logger()
        for i in range(10):
            time.sleep(.5)
            log.log(25, 'Process {} logging {}'.format(ids, i))
    
    if __name__ == '__main__':
        # Setup the logger
        log = util.get_logger()
        log.getEffectiveLevel()
        # You can setup a file instead of stdout in the StreamHandler
        ch = logging.StreamHandler(out)
        ch.setLevel(25)
        ch.setFormatter(logging.Formatter('%(processName)s - %(message)s'))
        log.addHandler(ch)
        log.setLevel(25)
    
        p1 = mp.Process(target=runner, args=(1,), name="Process1")
        p2 = mp.Process(target=runner, args=(2,), name="Process2")
    
        p1.start()
        p2.start()
    
        time.sleep(2)
        log.log(25, 'Some main process logging meanwhile')
    
        p1.join()
    

    级别 >20 允许避免从启动和停止进程中获取日志。
    如果参数 out 是一个打开的可写文件,Handler 可以直接登录文件。
    这避免了必须自己处理日志队列。 logging 模块中还有许多其他高级功能。

    使用multiprocessing 模块中的记录器来获取线程安全日志非常重要。

    【讨论】:

      猜你喜欢
      • 2011-08-29
      • 2013-03-20
      • 1970-01-01
      • 1970-01-01
      • 2013-12-19
      • 1970-01-01
      • 2014-07-10
      • 2020-03-03
      • 1970-01-01
      相关资源
      最近更新 更多