简体   繁体   English

如何通过队列传递子进程标准输出? 蟒蛇

[英]How can I pass a child processes stdout with queue? Python

I have a Logger class with the following: 我有一个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)

a main with the following: 具有以下内容的主体:

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

in File1: 在File1中:

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

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

in File2: 在File2中:

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

Okay, so here is my structure. 好的,这是我的结构。 What I am trying to do is get the stdout from the child process running testFunc() and put it into the queue. 我想做的是从运行testFunc()的子进程中获取标准输出,并将其放入队列中。 When the program returns to main, i want to read from the queue and write those contents to the log file. 当程序返回main时,我想从队列中读取并将这些内容写入日志文件。

I can't just do sys.stdout = Logger.Logger() in file 2 again, because that will just overwrite mains log file. 我不能只是再次在文件2中执行sys.stdout = Logger.Logger(),因为这只会覆盖电源日志文件。 What can I do to capture all of child processes stdout and put in queue? 如何捕获所有子进程stdout并将其放入队列?

One solution could be to use the logging module. 一种解决方案是使用logging模块。
A logger is disponible in multiprocessing.util and can be use to generate thread safe logs: 记录器在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()

The level >20 permits to avoid getting the logs from starting and stopping the processes. 级别> 20可以避免启动和停止日志。
The Handler can directly log in a file if the argument out is an open writable file. 如果参数out是打开的可写文件,则处理程序可以直接登录文件。
This avoid having to process by yourself the log queue. 这避免了必须自己处理日志队列。 There is also a lot of other high level functionalities in the logging module. logging模块中还有许多其他高级功能。

It is important to use the logger from the multiprocessing module to get the thread safe logs. 使用multiprocessing模块中的记录器来获取线程安全日志很重要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 python 如何使用队列在子进程和主进程之间传递数据? - Using python how can I pass data between child and main processes with Queue? 如何在Python的进程之间共享队列? - How can I share a Queue between processes in Python? 我怎么能等待子进程? - How can I wait for child processes? 在大型批处理中,如何使用池或队列优化流程? - How can I optimize processes with a Pool or Queue in large batch processing? 你能用Python队列线程或进程吗? - Can you Queue Threads or Processes in Python? 多处理:我怎样才能 ʀᴇʟɪᴀʙʟʏ 从子进程重定向标准输出? - multiprocessing: How can I ʀᴇʟɪᴀʙʟʏ redirect stdout from a child process? 如何捕获子进程的stdout输出? - How can I capture the stdout output of a child process? 如何使用 Python 的 concurrent.futures 跨多个进程对任务进行排队,每个进程都有自己的线程池? - How can I use Python's concurrent.futures to queue tasks across multiple processes each with their own thread pool? 当有从该队列启动的进程时,如何创建一个可以在执行时间修改的队列系统 - How do I create a queue system that can be modified in execution time while there are processes launched from this queue 如何杀死后台 python 进程? - How can i kill background python processes?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM