Results 1 to 6 of 6

Thread: Python: Break loop on keypress.

  1. #1
    Join Date
    Nov 2007
    Beans
    60
    Distro
    Ubuntu 9.10 Karmic Koala

    Python: Break loop on keypress.

    Is it possible to break a loop on pressing the space key?

  2. #2
    Join Date
    Mar 2005
    Location
    Haarlem, The Netherlands
    Beans
    363

    Re: Python: Break loop on keypress.

    Does this thread helps?

  3. #3
    Join Date
    Mar 2005
    Beans
    947
    Distro
    Ubuntu 12.04 Precise Pangolin

    Re: Python: Break loop on keypress.

    The simplest way to do a keyboard-interruptible loop is like so:

    Code:
    try:
        while True:
            pass # do the loop here
    except KeyboardInterrupt:
        pass # do cleanup here
    However, this is only interruptible by ^C, not space... and it (mostly) doesn't work under Windows.

  4. #4
    Join Date
    Nov 2005
    Location
    Sendai, Japan
    Beans
    11,296
    Distro
    Kubuntu

    Re: Python: Break loop on keypress.

    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.
    「明後日の夕方には帰ってるからね。」


  5. #5
    Join Date
    Dec 2004
    Location
    Manchester
    Beans
    2,086
    Distro
    Ubuntu Mate 15.10 Wily Werewolf

    Re: Python: Break loop on keypress.

    here is a minimal example with curses

    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)
    it takes a bit of extra code to set up, but it works.

    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.

  6. #6
    Join Date
    Dec 2004
    Location
    Manchester
    Beans
    2,086
    Distro
    Ubuntu Mate 15.10 Wily Werewolf

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •