[英]Using python how can I pass data between child and main processes with Queue?
[英]How can I pass a child processes stdout with queue? Python
我有一個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()
在File1中:
def execSubProc(target,queue):
target(queue)
q = multiprocess.Queue()
proc = multiprocess.Process(target=execSubProc, args=(testFunc,q))
proc.start()
proc.join()
在File2中:
def testFunc(queue)
#Some print statements
#I want to get these print statements in the queue for main process to read
好的,這是我的結構。 我想做的是從運行testFunc()的子進程中獲取標准輸出,並將其放入隊列中。 當程序返回main時,我想從隊列中讀取並將這些內容寫入日志文件。
我不能只是再次在文件2中執行sys.stdout = Logger.Logger(),因為這只會覆蓋電源日志文件。 如何捕獲所有子進程stdout並將其放入隊列?
一種解決方案是使用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是打開的可寫文件,則處理程序可以直接登錄文件。
這避免了必須自己處理日志隊列。 logging
模塊中還有許多其他高級功能。
使用multiprocessing
模塊中的記錄器來獲取線程安全日志很重要。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.