我需要在 Mac 和 Windows 上为 python 3 提供定时输入,如果用户没有时间,它会自动选择其中一个选项。我见过的问题的所有其他答案只有在用户按“Enter”键后才会终止。无论是否按下“Enter”键,我都需要它终止。
例如,在我的国际象棋程序中,如果5秒后没有输入,我需要它自动选择“Q”。另外,如果输入不在 [“Q”,“R”,“B”,“N”] 中,那么我还需要它来选择“Q”。
下面的代码不起作用。它会要求输入然后永远等待;计时器根本不工作。
def countdown():
global timer
timer = 5
for x in range(timer):
timer -= 1
time.sleep(1)
countdownThread = threading.Thread(target=countdown)
countdownThread.start()
while timer > 0:
promotedPiece = input("Promote to Q, R, B or N? > ").upper()
if timer == 0:
break
if timer == 0:
if promotedPiece not in ["Q", "R", "B", "N"]: # If not valid input, choose Queen
promotedPiece = "Q"
print("Queen auto selected")
Run Code Online (Sandbox Code Playgroud) python multithreading timer python-multithreading python-3.x