まず、私は python 2.7.5 と Windows x64 を使用しています。私のアプリはこれらのパラメーターを対象としています。
一定の時間が経過した後に raw_input をキャンセルする方法が必要です。現在、メイン スレッドで 2 つの子スレッドを開始しています。1 つはタイマー (threading.Timer) で、もう 1 つは raw_input を起動します。これらはどちらも、メイン スレッドが監視する Queue.queue に値を返します。次に、キューに送信されたものに作用します。
# snip...
q = Queue.queue()
# spawn user thread
user = threading.Thread(target=user_input, args=[q])
# spawn timer thread (20 minutes)
timer = threading.Timer(1200, q.put, ['y'])
# wait until we get a response from either
while q.empty():
time.sleep(1)
timer.cancel()
# stop the user input thread here if it's still going
# process the queue value
i = q.get()
if i in 'yY':
# do yes stuff here
elif i in 'nN':
# do no stuff here
# ...snip
def user_input(q):
i = raw_input(
"Unable to connect in last {} tries, "
"do you wish to continue trying to "
"reconnect? (y/n)".format(connect_retries))
q.put(i)
私がこれまでに行った調査によると、スレッドを「正しく」キャンセルすることはできないようです。プロセスはタスクに対して重すぎると感じますが、それが本当に必要な場合はプロセスを使用することに反対しません. 代わりに、タイマーがユーザー入力なしで終了した場合、stdin に値を書き込み、そのスレッドを正常に閉じることができると考えています。
では、子スレッドが入力を受け入れて正常に閉じるように、メイン スレッドから stdin に書き込むにはどうすればよいでしょうか。ありがとう!