0

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.

SilentGhost
  • 307,395
  • 66
  • 306
  • 293
Dwayne
  • 1
  • 1
  • 2
  • possible duplicate of [Keyboard input with timeout in Python](http://stackoverflow.com/questions/1335507/keyboard-input-with-timeout-in-python) – Lennart Regebro Feb 03 '11 at 20:34

2 Answers2

3

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 of input

Community
  • 1
  • 1
Daniel DiPaolo
  • 55,313
  • 14
  • 116
  • 115
  • Thanks ! And what would it be if I were waiting for a message (s.recv(1024)) ? I also need a solution to this problem. – Dwayne Feb 03 '11 at 17:14
  • If you're waiting on a socket, then the `select` solution in the linked question is probably your best bet: http://stackoverflow.com/questions/1335507/keyboard-input-with-timeout-in-python/2904057#2904057 – Daniel DiPaolo Feb 03 '11 at 17:50
0

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.

Community
  • 1
  • 1
Chris B.
  • 85,731
  • 25
  • 98
  • 139
  • Thanks ! As I am using Python 3, I think I have to use input. What would it be if I were waiting for a message (s.recv(1024)) ? – Dwayne Feb 03 '11 at 17:10