I have a script that uses mouse clicks so the console window is not active. Therefore if I want to terminate the loop I cannot simply use Ctrl-C to keyboard interrupt it.
How can I incorporate a check inside a loop to break it if a key is pressed? For example I want something of the form:
while True:
if key_pressed.ascii() == 27: #escape is pressed
break
print('foo')
I've tried using msvcrt
but it only works when the window is active. I've tried using pyHook but couldn't get it to work inside a loop.
EDIT: Here is an example of something that almost works the way I would like it to. However it doesn't doesn't exit properly after it's finished running (even with sys.exit()) and moreover when implemented in my actual code the pygame.event.pump() call seems to mess up the loop code. What am I doing wrong here?
import pyHook, pygame, sys
def OnKeyboardEvent(event):
if event.Ascii==27:
global shouldBreak
shouldBreak=True
hm = pyHook.HookManager()
hm.KeyDown = OnKeyboardEvent
hm.HookKeyboard()
shouldBreak=False
pygame.init()
while True:
pygame.event.pump()
if shouldBreak:
break
#loop code
print('foo')
#post loop code
print('bar')
sys.exit()