3

I tried:

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

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.

This is with python 3.

falsetru
  • 357,413
  • 63
  • 732
  • 636
Jonathan
  • 10,571
  • 13
  • 67
  • 103

3 Answers3

9

Why does the code not work?

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

How to solve it

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 specific solution that use 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)
falsetru
  • 357,413
  • 63
  • 732
  • 636
6

Here is a simple way using an alarm. When the time expires, the lambda function is called, which would raise a ZeroDivisionError.

from signal import signal, alarm, SIGALRM

signal(SIGALRM, lambda x, y: 1/0)
try:
    alarm(600)
    input("Press enter to continue.")
except ZeroDivisionError:
    print("timed out")
Feline
  • 773
  • 3
  • 14
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
4

Another way to do it is this:

from time import sleep
print("I'm executing")
try:
    print("Wake up Ctrl-C!")
    sleep(600)
except KeyboardInterrupt:
    print("I woke up!")
else:
    print("I'm executing again.")

Not the greatest of answers and it definitely feels like an abuse of exceptions, but it works.

tenq
  • 49
  • 1