gpt4 book ai didi

python - 我应该使用 Popen 的等待还是通信来读取 Python 3 子进程中的标准输出?

转载 作者:行者123 更新时间:2023-12-01 03:55:19 24 4
gpt4 key购买 nike

我正在尝试在 Python 3 中运行子进程并不断读取输出。

subprocess 的文档中在 Python 3 中我看到以下内容:

Popen.wait(timeout=None)

Wait for child process to terminate. Set and return returncode attribute. Warning This will deadlock when using stdout=PIPE and/or stderr=PIPE and the child process generates enough output to a pipe such that it blocks waiting for the OS pipe buffer to accept more data. Use communicate() to avoid that.

这让我觉得我应该使用 communicate因为来自标准输出的数据量非常大。然而,再次阅读文档显示了这一点:

Popen.communicate(input=None, timeout=None)...

Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached.

Note The data read is buffered in memory, so do not use this method if the data size is large or unlimited.

同样,以这种方式从子流程中读取标准似乎存在问题。有人可以告诉我运行子进程并读取其所有(可能大量)标准输出的最佳/最安全方法吗?

最佳答案

我认为你应该使用沟通。该消息警告您该方法的默认行为存在性能问题。事实上,popen 构造函数有一个缓冲区大小参数,可以调整该参数以提高大数据量的性能。

希望对你有帮助:)

关于python - 我应该使用 Popen 的等待还是通信来读取 Python 3 子进程中的标准输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37577819/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com