Search code examples
pythondebuggingpyscripter

How to check if the user pressed a key in Python without using getch()?


I would like to interrupt a loop if the user presses a particular key and continue executing after the loop. The following code should work when stdin is available.

While True:
    # Do stuff here.
    if msvcrt.kbhit():
        key = msvcrt.getch()
        if key == somekey:
            break

My problem is that stdin is not available in the PyScripter IDE debugger which I am using for development. Is there another way to do this that bypasses stdin? The solution can be Windows specific if necessary.

P.S. I'm using Python 2.7 on Windows 7 with PyScripter using the 'Remote' Python Engine (whatever that means).

P.P.S. I rewrote this question based on feedback from dbliss below.


Solution

  • In Windows, the following code should do the trick:

    import win32api
    import win32con
    
    print "Doing stuff; press F12 to interrupt."
    While True:
        # Do stuff here.
        if win32api.GetAsyncKeyState(win32con.VK_F12) != 0:
            break