stopping a while True: with the keyboard

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Wed Sep 26 00:19:47 EDT 2007


En Tue, 25 Sep 2007 22:19:08 -0300, patrick <puredata at 11h11.com> escribi�:

> i am looking for a way to break a while True: when pressing "s" on my
> keyboard. how can i do this?

Windows only: Using the msvcrt module:

   from msvcrt import kbhit, getch
   a, b = 1, 1
   while True:
     a, b = a+b, a
     print a
     if kbhit() and getch() in 'sS':
       print "\nThanks!"
       break

There is a portable getch recipe in the Python Cookbook:  
<http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/134892> that  
supposedly should work on Windows, Linux and Mac OSX too.

If you just want to break the loop, and don't care too much in which state  
your variables remain, you can use Ctrl-C and catch the KeyboardInterrupt:

   a, b = 1, 1
   try:
     while True:
       a, b = a+b, a
       print a
   except KeyboardInterrupt:
     print "\nThanks!"
   ... continue program ...

-- 
Gabriel Genellina




More information about the Python-list mailing list