如何在python中编写一个unix过滤器? [英] How do I write a unix filter in python?
问题描述
x
。 so_gen.py(生成一个我们可以观察的常量流):
pre $ import time
import sys
(bc):
sys.stdout.write(char)
sys.stdout.flush()
time.sleep(0.1)
so_filter.py(按照您的要求):
导入sys
而真:
char = sys.stdin.read(1)
如果不是char:
break
如果char!='x':
sys.stdout.write(char)
sys.stdout.flush()
尝试运行 python so_gen.py | python so_filter.py
看看它是什么。
I want to write a program that reads stdin (unbuffered) and writes stdout (unbuffered) doing some trivial char-by-char transformation. For the sake of the example let's say I want to remove all chars x
from stdin.
I don't know exactly what you mean by buffered in this context, but it is pretty simple to do what you are asking...
so_gen.py (generating a constant stream that we can watch):
import time
import sys
while True:
for char in 'abcdefx':
sys.stdout.write(char)
sys.stdout.flush()
time.sleep(0.1)
so_filter.py (doing what you ask):
import sys
while True:
char = sys.stdin.read(1)
if not char:
break
if char != 'x':
sys.stdout.write(char)
sys.stdout.flush()
Try running python so_gen.py | python so_filter.py
to see what it does.
这篇关于如何在python中编写一个unix过滤器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!