0

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()
user406579
  • 23
  • 3
  • Possible duplicate of [Applying low-level keyboard hooks with Python and SetWindowsHookExA](http://stackoverflow.com/questions/9817531/applying-low-level-keyboard-hooks-with-python-and-setwindowshookexa) – Peter Wood May 20 '17 at 16:00
  • pyHook has a wonderful tutorial (that you've linked to). If you have a specific problem with it you should include code, etc. (see http://stackoverflow.com/help/how-to-ask) – thebjorn May 20 '17 at 16:00
  • edited post with pyHook example – user406579 May 20 '17 at 16:40
  • I have no experience with Pygame, however, it's typical to add a keyboard listener in addition to your mouse listener such that when the user presses a key (event), maybe `esc` key, you break the loop. – GIZ May 20 '17 at 17:43
  • That is precisely what I'm trying to do. And it doesn't have to use pygame at all, I just found some example code that used pygame's event.pump and it seems to work better than pythoncom.PumpMessages() as that appears to just hang the function (I still need the loop to run). – user406579 May 20 '17 at 18:31

0 Answers0