Python keyboard events without GUI (non-blocking)
<p>I am trying to find a way to get KeyDown and KeyUp events in Python. With Pygame, this is easily done with <code>pygame.KEYDOWN</code> and <code>pygame.KEYUP</code>, but I am trying to find a way to do it without using a GUI.</p>

<p>Ideally, I would like to be able to define a function <code>isKeyDown(key)</code>, which would return <code>True</code> if <code>key</code> is currently being held down, or return <code>False</code> if it isn't, but either way, it would move on with the code (it would be non-blocking). For example:</p>

<pre><code>while True:
    if not isKeyDown("a"): #If 'a' isn't currently being pressed
         print ("You are not pressing 'a'")
    elif isKeyDown("a"): #If 'a' is being held down when this is run
         print ("You are pressing 'a'")
         print ("This is the end of this program")
         break
</code></pre>

<p>I've tried <code>msvcrt.getch()</code>, but that has two problems:</p>

<p>1) It stops the program until something is pressed, and</p>

<p>2) It doesn't really tell you if the key is being held down; it simply returns if the key is being pressed at the time. This can sometimes coincide since Windows repeats key presses when they are held down, but it is unlikely to happen when the <code>while</code> loop is being run at maximum speed.</p>

<p>I've also used <code>msvcrt.kbhit()</code>, but it sets itself to <code>1</code> if any key has been pressed and not read by <code>msvcrt.getch()</code>, and so that still runs into the problems of <code>msvcrt.getch()</code> and doesn't really return whether a key is actually currently being held down.</p>

<p>I am using Windows, so the <code>curses</code> module that many people have used to answer similar questions isn't available.</p>

<p>Is there a way to define such a <code>isKeyDown()</code> function in Windows without a GUI, preferably only using built-in modules? If this is not possible with the built-in Python modules, third-party modules would be okay, as long as they don't require a GUI.</p>

<p>Even using Pygame or Tkinter would be fine, as long as a way to turn off their GUIs.</p>

<p>If this is not possible, please tell me why, so I can stop looking for a solution (I have been trying to do little else for the past few days).</p>

<p>I am using Python 3.5.2 on a 64-bit Windows 10 laptop.</p>