从管道读取——有状态或无状态
reading from a pipe -- stateful or stateless
我需要编写一个 python 脚本来处理另一个程序的输出。即我必须做:
./other_program | ./my_scripts.py
我的问题是这个my_script.py
是不是state-less
。例如,我能否记住我处理的最后一行输出来自 ./other_program
,或者脚本将只处理当前行,完全不知道最后一行?
管道不知道“线”。字节从一端进入,相同顺序的相同字节从另一端出来。中间有一点(可配置的)缓冲区,但在使用它们时,请考虑它们是无缓冲的。
而面向线 I/O 发生在更高级别,例如在管道文件描述符上创建 C stdio FILE
对象时,或使用 readline 库(或类似库)时。或者——就像你的情况一样——Python stdio print
、writelines
和 readline
.
编辑 1:
这里有两个简单的python程序
writer.py
#!/usr/bin/env python3
if '__main__' == __name__:
import time
i = 0;
while True:
print(f'This is writer.py, writing a line number {i} to stdout', flush=True)
i += 1
time.sleep(0.25)
reader.py
#!/usr/bin/env python3
if '__main__' == __name__:
i = 0
while True:
l = input()
print( f'This is reader.py, a line number {i} was read from stdin with the following content\n> {l}\n' )
i += 1
用./writer.py | ./reader.py
测试它们
我需要编写一个 python 脚本来处理另一个程序的输出。即我必须做:
./other_program | ./my_scripts.py
我的问题是这个my_script.py
是不是state-less
。例如,我能否记住我处理的最后一行输出来自 ./other_program
,或者脚本将只处理当前行,完全不知道最后一行?
管道不知道“线”。字节从一端进入,相同顺序的相同字节从另一端出来。中间有一点(可配置的)缓冲区,但在使用它们时,请考虑它们是无缓冲的。
而面向线 I/O 发生在更高级别,例如在管道文件描述符上创建 C stdio FILE
对象时,或使用 readline 库(或类似库)时。或者——就像你的情况一样——Python stdio print
、writelines
和 readline
.
编辑 1:
这里有两个简单的python程序
writer.py
#!/usr/bin/env python3
if '__main__' == __name__:
import time
i = 0;
while True:
print(f'This is writer.py, writing a line number {i} to stdout', flush=True)
i += 1
time.sleep(0.25)
reader.py
#!/usr/bin/env python3
if '__main__' == __name__:
i = 0
while True:
l = input()
print( f'This is reader.py, a line number {i} was read from stdin with the following content\n> {l}\n' )
i += 1
用./writer.py | ./reader.py