[英]reading from a pipe — stateful or stateless
我需要编写一个 python 脚本来处理另一个程序的 output 。 即我必须这样做:
./other_program | ./my_scripts.py
我的问题是这个my_script.py
是否是state-less
。 例如,我是否可以记住我处理的 output 的最后一行来自./other_program
,或者脚本只会处理当前行,完全不知道最后一行?
管道不知道“线”。 字节 go 在一端输入,相同顺序的相同字节在另一端输出。 两者之间有一点(可配置的)缓冲区,但是在使用它们时,请考虑它们是无缓冲的。
面向行的 I/O 发生在更高级别,例如,在 pipe 文件描述符上创建 C stdio FILE
object 时,或使用类似的文件描述符,或使用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
测试它们
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.