5

まず、私は 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 に書き込むにはどうすればよいでしょうか。ありがとう!

4

1 に答える 1

10

threading.Thread.join メソッドを使用してタイムアウトを処理できます。機能させるための鍵は、以下に示すようにデーモン属性を設定することです。

import threading

response = None
def user_input():
    global response
    response = input("Do you wish to reconnect? ")

user = threading.Thread(target=user_input)
user.daemon = True
user.start()
user.join(2)
if response is None:
    print()
    print('Exiting')
else:
    print('As you wish')
于 2013-10-18T17:34:41.990 に答える