3

Beginner in python, how can I make a timer which prints out the time left, which also stops when a user presses and enters any key. Here is my code right now:\

import time

keep_going = input("Press any key to stop the timer")

for i in range(3):
print(i + 1),
time.sleep(1)

if keep_going != " ":
    break

But it doesn't work because the timer starts after the question is asked.

Laurel Ted
  • 61
  • 9
  • You may find this helpful: https://stackoverflow.com/q/45130837/4014959 and https://gist.github.com/PM2Ring/215147b4de22e158a7b1d78f40300031 although that code is designed for an ANSI/VT100 Terminal, so it probably won't work on Windows. – PM 2Ring May 20 '18 at 10:04

2 Answers2

2

This is not possible in a single threaded environment and with the command line. As it there's no mechanism to 'detect' if ANY KEY is pressed (without input).

import time


counter = 0
try:
    while True:
        print(counter + 1)
        counter += 1
        time.sleep(1)
except KeyboardInterrupt:
    print('You\'ve exited the program.')

The program will wait until Ctrl+C Keyboard interrupt is pressed.

Same works with the for loop.

import time


try:
    for i in range(3):
        print(i + 1)
        time.sleep(1)
except KeyboardInterrupt:
    print('You\'ve exited the program.')
innicoder
  • 2,612
  • 3
  • 14
  • 29
  • KeyboardInterrupt won't work when I press ctrl c on pycharm in the shell – Laurel Ted May 20 '18 at 20:28
  • Well, you're not really supposed to be using it that way, once you deliver it to the end user or another person you'll expect it to run it normally. Running it with Pycharm should be only for debugging reasons. Hope that helps. – innicoder May 20 '18 at 22:39
1

I would make a separate thread for a timer. Start the timer in that thread, and wait for an input in the main thread.

import time
import threading

def run_timer():
    flag = True
    for i in range(3):
        print(i + 1)
        time.sleep(1)
        if not flag:
            break

timer_thread = threading.Thread(target=run_timer)
timer_thread.daemon = True
timer_thread.start()

In the main thread, where a user inputs a key, you should set the flag accordingly.

Gene Byun
  • 188
  • 1
  • 9