我正在阅读 Mark Lutz 的 Programming Python,我偶然发现了这一点:
For pipe objects, the effect of iterators may be even more useful than simply avoiding loading the entire result into memory all at once: readlines will always block the caller until the spawned program is completely finished, whereas the iterator might not.
这是什么意思?
请您参考如下方法:
如果以 subprocess.Popen 为例。如果您调用一个将大量数据输出到 subprocess.PIPE 的命令,那么调用 proc.stdout.readlines() 将等待命令完全完成。
如果你将 iter 与 for line in iter(proc.stdout.readline,"") 一起使用,你会实时看到输出,并且避免将所有输出存储在内存中。
如果你必须处理输出的每一行,当输入进来时逐行处理会更有意义,使用 iter 允许你做而不是阻塞直到命令终止使用阅读线。
