Detect if key is down mac python
<p>I've googled all over the place.</p>

<p>I have a python application and I'd like to detect if a key is down (on OSX).</p>

<p>The only answers I've been able to find are either libraries for windows, or libraries that require an application window to be active (like pygame).</p>

<p>Similar to how pymouse has a position() method.</p>

<p>I'd like to be able to do something in my code like:</p>

<pre><code>if keyboard.keydown(&lt;key code&gt;):
  # do something
elif keyboard.keycode(&lt;some other keycode&gt;):
  # do something
</code></pre>

<p>On Mac.</p>

<p>Python comex with tkinter, a gui framework that includes cross-platform key press and release handling.  The gui part can be suppressed if one only wants the event handling.  This works as expected on my Windows machine.  It should work on your Mac.</p>

<pre><code>from time import sleep
import tkinter as tk
root = tk.Tk()
root.withdraw()  # Do not show root window.
spacedown = False
def press_s(dummy):
    global spacedown
    spacedown = True
    print('down')
def release_s(dummy):
    global spacedown
    spacedown = False
    print('up')
root.bind('&lt;KeyPress- &gt;', press_s)
root.bind('&lt;KeyRelease- &gt;', release_s)
while True:
    sleep(1)
    root.update()
    print('tick', 'down' if spacedown else 'up')
</code></pre>

<p>In the bind statements, replace the space <code></code> after the <code>-</code> with the key (such as <code>a</code> or <code>*</code>) or a <a href="http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/key-names.html" rel="nofollow">keyname</a>.  Whenever you want to detect the current state of the key, call root.update to process queued events and set keydown.</p>

python osx python-2.7