简体   繁体   English

流式多处理进程 output

[英]Streaming multiprocessing process output

I have a function that generates output before returning the result.我有一个 function 在返回结果之前生成 output。 While that function is running, I want to stream the intermediate output to a frontend, so a user is aware what's happening while waiting for the result.当 function 正在运行时,我想将 stream 中间 output 发送到前端,以便用户在等待结果时知道发生了什么。 I'm trying to accomplish this with Multiprocessing, but intermediate output and the result is printed at once at the end.我正在尝试使用 Multiprocessing 来完成此操作,但中间值为 output,最后会立即打印结果。 I can't find a comparable problem anywhere, so advice is much appreciated.我在任何地方都找不到类似的问题,因此非常感谢您的建议。 This is my undesirably behaving code so far:到目前为止,这是我行为不当的代码:

from multiprocessing import Process, Pipe
from sklearn.manifold import TSNE
import random
import io
import sys

def TSNE_transform():
    X = [[random.randint(1,9) for i in range(9)] for j in range(10)]
    model = TSNE(n_components=3, verbose=3)
    result = model.fit_transform(X)
    return result

if __name__ == '__main__':
    parent_conn, child_conn = Pipe()
    p = Process(target=TSNE_transform)
    p.start()
    while True:
        print(parent_conn.recv())
        if parent_conn.recv() == None:
            break
    p.join()

Function TSNE_transform is generating intermediate output. Function TSNE_transform正在生成中间体 output。

I also tried to redirect the stdout like this, but I'm not sure how that could be streamed to a frontend:我也尝试像这样重定向标准输出,但我不确定如何将其流式传输到前端:

old_stdout = sys.stdout

# Assign buffer to new_stdout
new_stdout = io.StringIO()

# Assign stdout to buffer
sys.stdout = new_stdout

X = [[random.randint(1,30) for i in range(30)] for j in range(100)]
model = TSNE(n_components=3, verbose=3)
result = model.fit_transform(X)

# Get values
output = new_stdout.getvalue()

# Revert to original stdout
sys.stdout = old_stdout

print(output)

Any help is welcome:)欢迎任何帮助:)

You should use a Queue in order to communicate with the Process.您应该使用Queue来与Process.
The simple example below is taken from the docs .下面的简单示例取自文档

import multiprocessing as mp

def foo(q):
    q.put('hello')

if __name__ == '__main__':
    ctx = mp.get_context('spawn')
    q = ctx.Queue()
    p = ctx.Process(target=foo, args=(q,))
    p.start()
    print(q.get())
    p.join() 

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM