Reputation: 35
I'm fairly new to python and am trying to make a basic stopwatch script. I want to be able to pause the stopwatch, but the time.sleep(1)
code which waits for the next number to be shown interferes with the keyboard event. BTW I'm using the python package 'keyboard' to get the event. I have tried threading but I can't pause the other thread as far as I know.
Here's my code:
import time, keyboard, sys
print('Stopwatch \n')
input('Press enter to start:')
def counter():
stopwatch = 0
while True:
time.sleep(1)
stopwatch += 1
print(stopwatch)
question()
def question():
while True:
if keyboard.is_pressed('p'):
print('\nPaused')
input('Press enter to resume:')
if keyboard.is_pressed('s'):
print('\nStopped')
sys.exit()
counter()
I don't necessarily need the question
function, but was experimenting to see if I could get it to work. I could combine the two functions.
Upvotes: 2
Views: 3216
Reputation: 54243
I've got some good news and some bad news. The bad news is that you can't do what you're trying to do the way you're trying to do it, for exactly the problem you're now facing. Python doesn't have a way of just pausing the execution of one function, it's all or nothing. You can solve this by implementing through multiprocessing
or threading
, but you're really just opening a can of worms to get into that before you're ready.
The good news is that you don't need to do all that. You're trying to find the difference between a start time and an end time, right? Let's boil it down to basics and do that.
import datetime
start = datetime.datetime.now()
input("Press enter to stop.")
stop = datetime.datetime.now()
result = (stop - start).total_seconds()
You can implement pausing by waiting for other actions (in a while True
loop as you've done above), getting the difference in seconds between start and stop and adding it to a running total.
Upvotes: 1