2012-02-27 7 views
3
while True: 
    mess = raw_input('Type: ') 
    //other stuff 

ユーザーは何も入力しませんが、//other stuffはできません。どうすれば他のものが実行されるのですか?ユーザーがその時点で何かを入力すると、混乱はその値を変更しますか?raw_inputに何か書き込むかどうかをユーザーが決定している間に他の処理を行う方法はありますか?

+1

[Pythonの他のスレッドによって上書きされることなく、raw_input()から入力を読み込む](http://stackoverflow.com/questions/2082387/reading-input-from-raw-input-without-having -the-prompt-over-other-th) –

+0

私はあなたの記事に出くわして、あなたの質問であなたを助けるためにいくつかの掘削をすることに決めました。あなたがこの記事を前に見つけたかどうかは分かりませんが、この記事が見つかりました。http://stackoverflow.com/questions/2082387/reading-input-from-raw-input-without-having-the-prompt-overwritten-by -other-thとユーザーjhackworthによる一番上の投票の答えはあなたが言及している問題に対処しているようです。私はこれが助けてくれることを願っていますし、少なくとも正しい方向にあなたを指していますように! – SMT

答えて

4

他のものをワーカースレッドに生成する必要があります。

import threading 
import time 
import sys 

mess = 'foo' 

def other_stuff(): 
    while True: 
    sys.stdout.write('mess == {}\n'.format(mess)) 
    time.sleep(1) 

t = threading.Thread(target=other_stuff) 
t.daemon=True 
t.start() 

while True: 
    mess = raw_input('Type: ') 

これは、グローバルとしてmessを使用する簡単な例です。ワーカースレッドとメインスレッド間でオブジェクトをスレッドセーフで渡すには、Queueオブジェクトを使用してスレッド間で物事を渡す必要があります。グローバルは使用しないでください。

import select 
import sys 

def raw_input_timeout(prompt=None, timeout=None): 
    if prompt is not None: 
     sys.stdout.write(prompt) 
     sys.stdout.flush() 
    ready = select.select([sys.stdin], [],[], timeout)[0] 
    if ready: 
     # there is something to read 
     return sys.stdin.readline().rstrip('\n') 

prompt = "First value: " 
while True: 
    s = raw_input_timeout(prompt, timeout=0) 
    if s is not None: 
     mess = s # change value 
     print(repr(mess)) 
     prompt = "Type: " # show another prompt 
    else: 
     prompt = None # hide prompt 
    # do other stuff 

ユーザーがmess値が変更されを入力します押すたびに:あなたは、ユーザー入力がselect.select()経由でUnix上で利用可能であるかどうかをポーリングすることができワーカースレッドを使用する代わりに

関連する問題