select
モジュールは、あなたが探している正確に何を達成しselect
と呼ばれる機能を提供しています。 select.select
は3つの引数を取る:
select.select(rlist, wlist, xlist)
各引数は、(例えば[sys.sdtin]
など)、ファイル記述子のリストであるべきであり、特定のIO操作が使用可能になるまで、それは次に待ち。IO操作は、r ead、w riteまたはその他の特定のファイル記述子のx ceptionです。これは、対応するリストのtuple
を、準備ができているファイル記述子で埋めて戻します。 sys.stdin
で待っている入力がある場合
ので、その関数はそうと同じように動作します:IO操作があるまでは、デフォルトで機能がお待ちしておりますので、
>>> import select
>>> import sys
>>>
>>> select.select([sys.stdin], [], [])
([sys.stdin], [], [])
>>>
は、それ自体では、これはあなたの問題を解決していません利用可能です。しかし、重要なことに、select.select
にはオプションのtimeout
という引数があり、これは放棄するまでの待機時間を示します。タイムアウトをゼロに設定するだけで、プログラムフローをブロックせずに入力を確認できます。
のは、sys.stdin
で待っている入力がない例を見てみましょう:
>>> import select
>>> import sys
>>>
>>> timeout = 0
>>> select.select([sys.stdin], [], [], timeout)
([], [], [])
>>>
我々は唯一のそのタプルの最初の要素をしたいことを知っての我々は、if文有用なものにする準備が整いました(入力ストリーム)
while sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
sys.stdin.readline()
::入力ストリームをクリアするだけで、いくつかの反復を必要とする意味
if sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
print('Input is waiting to be read.')
それでは、あなたがあなたの問題のために頼むものを達成するために私達の機能を発揮させ
def clear_input(stream, timeout=0):
'''Takes an input stream and discards each line in the buffer.
The given timeout denotes how long in seconds to wait for
further input when none is available.
'''
while stream in select.select([stream], [], [], timeout)[0]:
stream.readline()
を::
そして、私たちはもちろん、任意の入力ストリームでこれを使用することができますが、その機能にそれを置くことができます
import select
import sys
import time
def clear_input(stream, timeout=0):
while stream in select.select([stream], [], [], timeout)[0]:
stream.readline()
if __name__ == '__main__':
print('Type some lines now. They will be ignored.')
time.sleep(5)
print('Clearing input.')
clear_input(sys.stdin)
user_input = raw_input('Please give some fresh input: ')
print(user_input)
clear_input
関数は、入力ストリームを消去するための非ブロッキング方法として使用でき、Python2とPython3で動作するはずです。
'fflush(stdin)'はUBです。 –
空の入出力ストリーム*はありません**ストリーム**です。次のことを考慮してください。 './myprog dev/random';その標準ストリームの終わりが見えますか? – joop
これをWindows上でプログラミングするには、Linuxで動かす必要があります... – Tom