4

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.

1
  • you're going to need a thread, probably. Commented Oct 22, 2013 at 3:18

3 Answers 3

10

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)
Sign up to request clarification or add additional context in comments.

Comments

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")

2 Comments

signal.alarm is only available in Unix.
Sadly some people are still using non-POSIX compliant OS
5

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.

1 Comment

It's not an abuse, it's just not related to the question. Where is the user input here?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.