2017-08-23 10 views
1

私はstdinから文字をPythonスクリプトで読み込もうとしています。何かが利用可能になったときにいつも通知するためにselect.select()を使用しています。私は理解できない行動に直面している。それはおそらく例で最もよく説明されています。まず、ここではサンプルセレクトコードです:複数の文字がstdinで入力されている場合にのみ、上記の見ることができるようにPythonの奇妙なselect.select()の動作

/tmp$ python test.py 
AAAA  # I type in a few chars then ENTER. 
Read: A # Only one char is detected :(
BBBB  # I type in more characters 
Read: A # Now all the previous characters are detected!? 
Read: A 
Read: A 
Read: # ('\n' is read which I want) 

Read: B # Wait, where are the other Bs? 
CCCC  # I need to type more chars so that BBB is printed, and the first C. 

:今ここに

import select 
import sys 

while True: 
    r, w, e = select.select([sys.stdin], [], []) 
    print "Read: %s" % sys.stdin.read(1) 

スクリプトの実行例であります最初のものが印刷されます。次に、さらに多くの文字が追加されると、前の入力の残りの文字列と新しい入力の最初の文字列がすべて印刷されます。

私は間違っていますか?

+0

何(彼らが必要としている?) – Adi219

+0

そうでもありません。 'sys.stdin.read'は' r [0] .read'と置き換えることができますが、問題は変わりません。 – executifs

+0

あなたはどんなPythonバージョンですか? – user2357112

答えて

1

select.selectは、Pythonファイルオブジェクト(たとえばsys.stdin)でのバッファリングを認識しません。これはsys.stdinから読み取ろうとすると奇妙な相互作用するけれどもあなたは、完全にファイルオブジェクトをバイパスすることができます:e`、W、R 'の重要性である

import select 
import os 
import sys 

while True: 
    r, w, e = select.select([sys.stdin], [], []) 
    print os.read(sys.stdin.fileno(), 1) 
+0

これはまさに私が欲しかったものです。これを理解してくれてありがとう、私はこの1つに私の髪を引き出していた。 – executifs