Pythonでユーザーからの入力を一定時間だけ待つ方法について説明します。この機能は、ユーザーが一定時間内に応答しない場合にプログラムが自動的に進行するようにするために使用されます。
selectモジュールを使用する方法
Unix/Linuxでは、selectモジュールを使用して一定時間待つことができます。以下にそのコードスニペットを示します。
import sys
from select import select
print("Press any key to configure or wait 5 seconds...")
timeout = 5
rlist, _, _ = select([sys.stdin], [], [], timeout)
if rlist:
print("Config selected...")
else:
print("Timed out...")
ただし、Windowsではこの方法は動作しません。Windowsでは、msvcrtモジュールを使用する必要があります。
msvcrtモジュールを使用する方法
Windowsでは、msvcrtモジュールを使用して一定時間待つことができます。以下にそのコードスニペットを示します。
import sys
import time
import msvcrt
timeout = 5
startTime = time.time()
inp = None
print("Press any key to configure or wait 5 seconds...")
while True:
if msvcrt.kbhit():
inp = msvcrt.getch()
break
elif time.time() - startTime > timeout:
break
if inp:
print("Config selected...")
else:
print("Timed out...")
threadingモジュールを使用する方法
threadingモジュールを使用して一定時間待つこともできます。以下にそのコードスニペットを示します。
import threading
import time
import sys
class MyThread(threading.Thread):
def __init__(self, threadID, name, counter, f):
super().__init__()
self.threadID = threadID
self.name = name
self.counter = counter
self.func = f
def run(self):
self.func()
class KeyboardMonitor:
def __init__(self):
self.keepGoing = True
def wait4KeyEntry(self):
while self.keepGoing:
s = input("Type q to quit: ")
if s == "q":
self.keepGoing = False
これらの方法を使用することで、Pythonで一定時間ユーザー入力を待つことができます。それぞれの方法には特性があるので、適切な方法を選択してください。