while 循环一段时间
我正在用 Python 编程。我有这样一个 while 循环,
b=time.clock()
while time.clock()-b<3 :
input("input")
我想在 3 秒后结束 while 循环,即使用户尚未输入任何内容!我怎样才能做到这一点?
编辑:如果我有 data=s.recv(1024)
,其中 s 是套接字,而不是 input("input")
,那会怎么样?代码>?
对于这样的问题有通用的解决方案吗?
编辑2:我正在使用Python 3。
I am programming in Python. I have such a while loop
b=time.clock()
while time.clock()-b<3 :
input("input")
I want to end the while loop after exactly 3 seconds, even if the user has not yet entered anything ! How can I do that?
Edit: What would it be if I had data=s.recv(1024)
where s is a socket, rather than input("input")
?
Is there a general solution to such a problem?
Edit2: I am using Python 3.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
input
阻止用户输入,因此您必须实现某种异步方式来触发超时事件(或在用户输入上触发)幸运的是,这个答案似乎就是这样!
编辑:如果您不使用 Python 3,您可能应该使用
raw_input
而不是input
input
blocks on user input, so you'll have to implement some asynchronous way to trigger the timeout event (or trigger on user input)Luckily, this SO answer seems to have just the thing!
edit: and if you're not using Python 3, you should probably be using
raw_input
instead ofinput
您不能使用
输入
。input
阻塞等待用户输入内容;当它处于阻塞状态时,您无法对正在发生的事情进行任何编程控制。有多种方法可以自己触发信号(如此处,如其他地方所建议)但这有点复杂。一般来说,您希望在这种情况下使用
raw_input
,尽管它也遇到同样的问题。如果您正在编写一个严肃的程序来与用户交互,您将需要使用一个真正的 GUI 框架,它将允许您以更直接的方式完成这些事情。You can't, using
input
.input
blocks waiting for the user to type something; while it's blocking, you don't have any programmatic control over what's going on. There are ways to trigger the signal yourself (as here, as suggested elsewhere) but that's kind of convoluted.In general, you want to be using
raw_input
in this situation, although it suffers from the same problem. And if you're writing a serious program to interact with the user, you'll want to use a real GUI framework, which will allow you to do these things in a more straight-forward way.