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

发布于 2025-02-13 20:15:38 字数 861 浏览 2 评论 0原文

我正在尝试从ProcessPoolExecutor捕获所有输出。

想象一下,您有一个文件func.py

print("imported")  # I do not want this print in subprocesses

def f(x):
    return x

然后,您可以使用ProcessPoolExecutor运行该功能,就像


from concurrent.futures import ProcessPoolExecutor
from func import f  # ⚠️ the import will print! ⚠️

if __name__ == "__main__":
    with ProcessPoolExecutor() as ex:  # ⚠️ the import will happen here again and print! ⚠️
        futs = [ex.submit(f, i) for i in range(15)]
        for fut in futs:
            fut.result()

现在我可以使用EG,contextLib捕获第一个导入的输出。但是,Redirect_stdout,但是,我也想捕获子过程中的所有输出,然后将它们重定向到主过程的stdout。

在我的真实用例中,我会收到要捕获的警告,但是简单的印刷品会重现问题。

这与防止以下错误相关。

I am trying to capture all output from a ProcessPoolExecutor.

Imagine you have a file func.py:

print("imported")  # I do not want this print in subprocesses

def f(x):
    return x

then you run that function with a ProcessPoolExecutor like


from concurrent.futures import ProcessPoolExecutor
from func import f  # ⚠️ the import will print! ⚠️

if __name__ == "__main__":
    with ProcessPoolExecutor() as ex:  # ⚠️ the import will happen here again and print! ⚠️
        futs = [ex.submit(f, i) for i in range(15)]
        for fut in futs:
            fut.result()

Now I can capture the output of the first import using e.g., contextlib.redirect_stdout, however, I want to capture all output from the subprocesses too and redirect them to the stdout of the main process.

In my real use case, I get warnings that I want to capture, but a simple print reproduces the problem.

This is relevant to prevent the following bug https://github.com/Textualize/rich/issues/2371.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文