[英]python: multiprocessing.Pipe and redirecting stdout
我正在使用multiprocessing
包來生成第二個進程,我想從中將 stdout 和 stderr 重定向到第一個進程。 我正在使用multiprocessing.Pipe
對象:
dup2(output_pipe.fileno(), 1)
其中output_pipe
是multiprocessing.Pipe
一個實例。 但是,當我嘗試在另一端閱讀時,它就掛了。 我嘗試使用有限制的Pipe.recv_bytes
進行讀取,但這會引發OSError
。 這是可能的還是我應該切換到一些較低級別的管道功能?
在Python 2.7中進行實驗后,我得到了這個工作示例。 使用os.dup2
管道的文件描述符被復制到標准輸出文件描述符,並且每個print
函數最終都寫入管道。
import os
import multiprocessing
def tester_method(w):
os.dup2(w.fileno(), 1)
for i in range(3):
print 'This is a message!'
if __name__ == '__main__':
r, w = multiprocessing.Pipe()
reader = os.fdopen(r.fileno(), 'r')
process = multiprocessing.Process(None, tester_method, 'TESTER', (w,))
process.start()
for i in range(3):
print 'From pipe: %s' % reader.readline()
reader.close()
process.join()
輸出:
From pipe: This is a message!
From pipe: This is a message!
From pipe: This is a message!
現有答案適用於原始文件描述符,但這對於使用 Pipe.send() 和 recv 可能很有用:
class PipeTee(object):
def __init__(self, pipe):
self.pipe = pipe
self.stdout = sys.stdout
sys.stdout = self
def write(self, data):
self.stdout.write(data)
self.pipe.send(data)
def flush(self):
self.stdout.flush()
def __del__(self):
sys.stdout = self.stdout
要使用此功能,在你的多進程函數來創建對象,通過它的寫入側multiprocessing.Pipe
,然后在父進程使用讀出側recv
,采用poll
,以檢查是否存在的數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.