Python 子进程管道

时间:2021-01-18 04:38:15

标签: python subprocess pipe popen

我只是想对subprocess.popenpipes有更多的了解。主要问题是

  1. 它在哪里保存管道的内容(内存或文件系统)?
  2. 它是否像一个迭代器,当我阅读/迭代它时,那些内容会被删除?
  3. 如果我在 Popen 中使用 bufsize,它是如何工作的?在读取管道中的某些内容之前,它是否会暂停/阻止子进程?

例如,假设我有以下 main.py

import subprocess
import time


class SubprocessReader():
    def __init__(self):
        self.proc = subprocess.Popen(['python', "mysubprocess.py"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

    def __iter__(self):
        return self

    def __next__(self):
        while True:
            line = self.proc.stdout.readline()
            if not line:
                raise StopIteration
            return line


a = SubprocessReader()
for word in a:
    print(word)
    time.sleep(0.5)

并且 mysubprocess.py 包含:

for x in range(1000000000):
    print("writing {}".format(x))

所以在这个例子中,子进程写入管道的速度要快得多,因为父进程正在读取它并休眠半秒。我认为这会在一段时间后使用大量内存/空间。不过,我没有看到 htop 有任何额外的内存使用。那么问题来了,子进程的标准输出/打印输出保存到哪里?如果我从 main.py 中删除睡眠,从技术上讲它不会使用任何额外的内存/空间吗?因为一旦子进程写入管道,主进程就会读取它并将其从内存中删除?是这样操作的吗?

如果我在 main.py 中这样做而不是循环

a = SubprocessReader()
a.proc.wait()

我仍然没有看到内存或htop有任何增加。所以我真的很困惑数据保存在哪里。

最后,如果我使用 bufsize,它会在子进程达到那个大小时阻塞它,并在读取某些内容时继续吗?

0 个答案:

没有答案
相关问题