我试过了:

from time import sleep
while sleep(3):
    input("Press enter to continue.")

但它似乎不起作用。我希望程序等待用户输入,但如果 10 分钟后没有用户输入,则继续执行程序。

这是python 3。

最佳答案

为什么代码不起作用?
time.sleep 不返回任何内容; time.sleep(..) 的值变为 Nonewhile 循环体未执行。

如何解决

如果您使用的是 Unix,则可以使用 select.select

import select
import sys

print('Press enter to continue.', end='', flush=True)
r, w, x = select.select([sys.stdin], [], [], 600)

否则,您应该使用线程。

使用 msvcrt 的 Windows 特定解决方案 :
import msvcrt
import time

t0 = time.time()
while time.time() - t0 < 600:
    if msvcrt.kbhit():
        if msvcrt.getch() == '\r': # not '\n'
            break
    time.sleep(0.1)

关于Python:WAITING用户输入,如果10分钟后没有输入,则继续程序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19508353/

10-11 22:27
查看更多