原始输入和超时 [英] raw_input and timeout

查看:30
本文介绍了原始输入和超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做一个raw_input('Enter something: .').我希望它休眠 3 秒钟,如果没有输入,则取消提示并运行其余代码.然后代码循环并再次实现raw_input.如果用户输入诸如q"之类的内容,我也希望它中断.

I want to do a raw_input('Enter something: .'). I want it to sleep for 3 seconds and if there's no input, then cancel the prompt and run the rest of the code. Then the code loops and implements the raw_input again. I also want it to break if the user inputs something like 'q'.

推荐答案

有一个不使用线程的简单解决方案(至少不是明确地):使用 select 知道什么时候需要从标准输入读取:

There's an easy solution that doesn't use threads (at least not explicitly): use select to know when there's something to be read from stdin:

import sys
from select import select

timeout = 10
print "Enter something:",
rlist, _, _ = select([sys.stdin], [], [], timeout)
if rlist:
    s = sys.stdin.readline()
    print s
else:
    print "No input. Moving on..."

Edit[0]:显然这个 在 Windows 上不起作用,因为 select() 的底层实现需要一个套接字,而 sys.stdin 不是.感谢您的提醒,@Fookatchu.

Edit[0]: apparently this won't work on Windows, since the underlying implementation of select() requires a socket, and sys.stdin isn't. Thanks for the heads-up, @Fookatchu.

这篇关于原始输入和超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆