0

How can I run a loop in Python and code it to stop when the user press a button (not ctr+c)?

FRD
  • 2,254
  • 3
  • 19
  • 24
  • That depends. Do you want this to be a free-running loop, or one that waits for some user input each time through the loop? And, what kind of button input? Mouse button? Keyboard? Power button? – Greg Hewgill Oct 17 '10 at 23:20
  • 4
    Possible solution: http://stackoverflow.com/questions/3894408/easiest-way-to-pause-a-command-line-python-program/3894439#3894439 . A minor change in the linked code can make the program pause/unpause when a key is pressed. – unutbu Oct 17 '10 at 23:21
  • I want a free-running loop. The input can be anyone, or specific. But, is that possible? – FRD Oct 17 '10 at 23:41

1 Answers1

0

I had a similar problem, found this code excerpt that helped me.

#!/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)

The problem of course is that using curses will prevent a lot of other things (like print) from working but there are ways around that.

Troy Rockwood
  • 5,875
  • 3
  • 15
  • 20