I want to make a stopwatch in python 3.3 that continues to count until you press a button or something, it should then stop counting. This is my code:
seconds = 0
minutes = 0
continued = 0
while continued != 1:
print(minutes, ":", seconds)
time.sleep(1)
if seconds == 59:
seconds = 0
minutes = minutes + 1
else:
seconds = seconds + 1
without using CTRL + C
I am using no GUI or anything, just pure python code running in command prompt using IDLE.
Attempting to waiti for a keypress in a loop, without threading or timers/signals will block the loop.
One way to have the main loop continue processing (stopwatch) while waiting for a keypress is via threading. A preliminary search brought me to an ActiveState recipe, although I found the solution from this thread.
import threading, os, time, itertools, queue
try : # on windows
from msvcrt import getch
except ImportError : # on unix like systems
import sys, tty, termios
def getch() :
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try :
tty.setraw(fd)
ch = sys.stdin.read(1)
finally :
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
commands = queue.Queue(0)
def control(commands) :
while 1 :
command = getch()
commands.put(command) # put the command in the queue so the other thread can read it
# don't forget to quit here as well, or you will have memory leaks
if command == " " :
print "Stop watch stopped!"
break
def display(commands):
seconds = 0
minutes = 0
command = ""
while 1 :
# parsing the command queue
try:
# false means "do not block the thread if the queue is empty"
# a second parameter can set a millisecond time out
command = commands.get(False)
except queue.Empty, e:
command = ""
# behave according to the command
if command == " " :
break
print(minutes, ":", seconds, end="")
if seconds == 59:
seconds = 0
minutes = minutes + 1
else:
seconds = seconds + 1
time.sleep(1)
# start the two threads
displayer = threading.Thread(None,display,None, (commands,),{})
controler = threading.Thread(None, control, None, (commands,), {})
if __name__ == "__main__" :
displayer.start()
controler.start()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With