Is it possible to break a loop on pressing the space key?
Is it possible to break a loop on pressing the space key?
Does this thread helps?
The simplest way to do a keyboard-interruptible loop is like so:
However, this is only interruptible by ^C, not space... and it (mostly) doesn't work under Windows.Code:try: while True: pass # do the loop here except KeyboardInterrupt: pass # do cleanup here
It depends what exactly you mean by "break". If you mean "instantly terminate", then no. If you can wait until the next loop iteration, then maybe. You'd need a thread that sets some global variable to True when the space key is pressed (maybe with dbus?), and the normal worker thread where you would add a while not space_pressed: loop.
here is a minimal example with curses
it takes a bit of extra code to set up, but it works.Code:#!/usr/bin/env python import curses def main(win): win.nodelay(True) # make getkey() not wait x = 0 while True: #just to show that the loop runs, print a counter win.clear() win.addstr(0,0,str(x)) x += 1 try: key = win.getkey() except: # in no delay mode getkey raise and exeption if no key is press key = None if key == " ": # of we got a space then break break #a wrapper to create a window, and clean up at the end curses.wrapper(main)
also using curses will mess with all the input and output. you can't use print anymore, you have to use addstr and give a position.
Bookmarks