I am trying to make a simple timer which counts up until it is interrupted by keyboard input.
right now I am using CTRL+C to stop the timer, but I would like to do something more simple like hitting space or enter or "any key". I hear this can be done with the threading module, but after several attempts I clearly do not know what I am doing with that.
this is my current code:
def countup():
try:
a=0
for i in range(1000000) :
print i,'\r',
time.sleep(1)
except KeyboardInterrupt:
Z = raw_input("restart timer?" )
if Z == "Y" or Z == "y" :
countup()
Using thread and terminal capabilities you can write (press any key to stop):
Let's clarify a bit:
thread.start_new_thread()
create a new thread usinginput_thread()
as start function. Whilethread.interrupt_main()
raiseKeyboardInterrupt
in the main thread.termios.tcgetattr()
return the current terminal attribute.~termios.ICANON
unset the canonical mode and~termios.ECHO
prevent input print thentermios.tsetattr()
act the change.Alternatively, on Windows,
getch()
from msvcrt can be use in place ofread_key()
Reference
There are two problems with your code as it stands:
The problem is that you need to attempt to read from stdin, but not wait until input appears there if there isn't any to begin with. This page provides a good description of how to do this.
Based on the link above, this code should do the trick to make the countup stop if you hit enter: