如何在Python中实现`cat`

时间:2016-11-30 17:10:39

标签: python pipe

有人可以举一个用Python实现的cat的工作示例吗?该程序应该从stdin读取并写入stdout。我的问题是:如何从stdin中读取所有剩余数据(不一定用换行符终止)?我应该使用非阻塞IO,关闭缓冲还是做其他事情?

C实现:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/select.h>

int main()
{

    fd_set set;
    struct timeval timeout;

    FD_ZERO(&set);
    FD_SET(0, &set);

    timeout.tv_sec = 10;
    timeout.tv_usec = 0;

    char buf[1024];

    while (1) {
        select(FD_SETSIZE, &set, NULL, NULL, &timeout);
        int n = read(0, buf, 1024);
        if (n == 0) {
            exit(0);
        }
        write(1, buf, n);
    }

    return 0;
}

测试程序:

import time

i = 0
while True:
    time.sleep(0.2)
    print(i, end='', flush=True)
    i += 1

预期结果:将测试程序管道到cat.py应该每0.2秒输出一个数字。结果与内置cat或上面的C实现一样符合预期。

1 个答案:

答案 0 :(得分:1)

好吧,这不是很痛苦。

import os
import select
import sys

while True:
    ready, _, _ = select.select([sys.stdin], [], [], 0.0)
    if sys.stdin in ready:
        data = os.read(sys.stdin.fileno(), 4096)
        if len(data) == 0:
            break
        os.write(sys.stdout.fileno(), data)
相关问题