如何在python中编写一个unix过滤器? [英] How do I write a unix filter in python?

查看:132
本文介绍了如何在python中编写一个unix过滤器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个程序读取标准输入(无缓冲),并写入标准输出(无缓冲)做一些简单的逐字符转换。为了这个例子,我们假设我想从标准输入中删除所有的字符 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆