我只是想对subprocess.popen
和pipes
有更多的了解。主要问题是
例如,假设我有以下 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
,它会在子进程达到那个大小时阻塞它,并在读取某些内容时继续吗?