本文介绍了Python:等待用户输入,如果10分钟后没有输入,则继续程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试过了:

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

但是好像不行.我希望程序等待用户输入,但如果 10 分钟后没有用户输入,则继续执行程序.

But it doesn't seem to work. I want the program to await user input, but if there's no user input after 10 minutes, continue with the program anyway.

这是使用python 3.

This is with python 3.

推荐答案

为什么代码不起作用?

time.sleep 什么都不返回;time.sleep(..) 的值变为 None;while 不执行循环体.

time.sleep returns nothing; the value of the time.sleep(..) become None; while loop body is not executed.

如何解决

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

If you're on Unix, you can use select.select.

import select
import sys

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

否则,您应该使用线程.

Otherwise, you should use thread.

Windows 特定解决方案,使用 msvcrt:

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:等待用户输入,如果10分钟后没有输入,则继续程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 07:25