2011-03-15 21 views
3

我想用Python 3腳本(在Linux上)逐行處理運行程序的輸出(認爲tail -f)。將一個程序的latin-1編碼輸出配置到Python 3腳本

的程序輸出,這是越來越管道輸送到腳本,在拉丁語-1進行編碼,所以,在Python 2中,我使用的codecs模塊的sys.stdin適當的輸入進行解碼:

#!/usr/bin/env python 
import sys, codecs 

sin = codecs.getreader('latin-1')(sys.stdin) 
for line in sin: 
    print '%s "%s"' % (type (line), line.encode('ascii','xmlcharrefreplace').strip()) 

這工作:

<type 'unicode'> "Hi! &#246;&#228;&#223;" 
... 

然而,在Python 3,sys.stdin.encodingUTF-8,如果我只是從標準輸入讀取天真:

#!/usr/bin/env python3 
import sys 

for line in sys.stdin: 
    print ('type:{0} line:{1}'.format(type (line), line)) 

我得到這個錯誤:

UnicodeDecodeError: 'utf8' codec can't decode byte 0xf6 in position 4: invalid start byte

我如何讀取非UTF-8文本數據管道在Python 3標準輸入?

回答

3
import sys 
import io 

with io.open(sys.stdin.fileno(),'r',encoding='latin-1') as sin: 
    for line in sin: 
     print ('type:{0} line:{1}'.format(type (line), line)) 

產生

type:<class 'str'> line:Hi! öäß 
+0

工程就像一個魅力,我可以直接處理文本,完美!謝謝! – phoibos 2011-03-15 02:18:32

2

看看這個鏈接的文檔中:sys.stdin。相關部分是:

The standard streams are in text mode by default. To write or read binary data to these, use the underlying binary buffer. For example, to write bytes to stdout, use sys.stdout.buffer.write(b'abc'). Using io.TextIOBase.detach() streams can be made binary by default. This function sets stdin and stdout to binary:

def make_streams_binary(): 
    sys.stdin = sys.stdin.detach() 
    sys.stdout = sys.stdout.detach() 

這樣做後,你可以編碼的二進制輸入任何你想要的編碼。


也看到這個帖子: How to set sys.stdout encoding in Python 3?
從該職位的建議是使用方法:

sys.stdin = codecs.getreader("utf-8")(sys.stdin.detach()) 
相關問題