2016-11-30 52 views
-4

任何人都可以給出一個在Python中實現的cat的工作示例嗎?這個程序應該從標準輸入讀取並寫入標準輸出。我的問題是:如何從標準輸入讀取所有剩餘的數據(不一定以換行符終止)?我應該使用非阻塞IO,關閉緩衝,還是做其他事情?如何在Python中實現`cat`

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實現一樣。

+0

我想你應該嘗試inbuild蟒蛇** ** SYS庫'進口SYS 數據= sys.stdin.read()'和'sys.stdout' –

+0

通常,'echo'從標準輸入讀取寫入&標準輸出。 'cat'將從文件讀取並寫入標準輸出(http://man7.org/linux/man-pages/man1/cat.1.html)。只需搜索如何從Python中的文件中讀取即可。 –

+0

@TusharNiras'sys.stdin.read()'返回一個'str'。他們也使用「字節」嗎? – Cyker

回答

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)