Mobalized
Mobalized

Reputation: 11

Stopping while loop with keystroke

Complete noob. I've read through some previous questions and tried implementing suggestions however haven't got it to work. I'm writing my first Python program and want to be able to press a key to stop the program from running aside from CTRL+C. (Forgive any indents in the code I'm pasting below as it is not necessarily the same as what I have in IDLE.)

x=int(input('Please Input a number... \n'))

while True:
  try:
    while x!=5:
        if x<5:
            x=x+1
            print ('Your value is now %s'%x)
            if x==5:
                print('All done, your value is 5')

        elif x>5:
            x=x-1
            print('Your value is now %s'%x)
            if x==5:
                print('All done, your value is 5')
  except KeyboardInterrupt:
      import sys
      sys.exit(0)

Upvotes: 1

Views: 90

Answers (1)

Kevin
Kevin

Reputation: 76194

There's no built-in way to detect keypresses in a non-blocking manner, but there may be third-party modules that can query your OS for keyboard state. For instance, Windows has Pywin32. Example implementation:

import time
import win32api

def is_pressed(key):
    x = win32api.GetKeyState(key)
    return (x & (1 << 8)) != 0

print "Beginning calculation. Press the Q key to quit."
while not is_pressed(ord("Q")):
    print "calculating..."
    time.sleep(0.1)
print "Finished calculation."

Upvotes: 1

Related Questions