捕获/重定向 ProcessPoolExecutor 的所有输出

joh*_*tis 5 python subprocess process-pool

我正在尝试捕获ProcessPoolExecutor.

\n

想象你有一个文件func.py

\n
print("imported")  # I do not want this print in subprocesses\n\ndef f(x):\n    return x\n
Run Code Online (Sandbox Code Playgroud)\n

然后你用ProcessPoolExecutor类似的方式运行该函数

\n
\nfrom concurrent.futures import ProcessPoolExecutor\nfrom func import f  # \xe2\x9a\xa0\xef\xb8\x8f the import will print! \xe2\x9a\xa0\xef\xb8\x8f\n\nif __name__ == "__main__":\n    with ProcessPoolExecutor() as ex:  # \xe2\x9a\xa0\xef\xb8\x8f the import will happen here again and print! \xe2\x9a\xa0\xef\xb8\x8f\n        futs = [ex.submit(f, i) for i in range(15)]\n        for fut in futs:\n            fut.result()\n
Run Code Online (Sandbox Code Playgroud)\n

现在我可以使用例如捕获第一次导入的输出contextlib.redirect_stdout,但是,我也想捕获子进程的所有输出并将它们重定向到主进程的标准输出。

\n

在我的实际用例中,我收到了想要捕获的警告,但简单的打印就重现了该问题。

\n

这与防止以下错误相关:https://github.com/Textualize/rich/issues/2371

\n