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
  • 336,967
  • 57
  • 673
  • 597
Jonathan
  • 9,822
  • 12
  • 51
  • 94

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
  • 336,967
  • 57
  • 673
  • 597
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
  • 575
  • 2
  • 14
John La Rooy
  • 281,034
  • 50
  • 354
  • 495
3

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
  • 39
  • 1