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>The only way I could think of is <a href="https://docs.python.org/2/library/tty.html" rel="nofollow">tty</a> or <a href="https://docs.python.org/2/library/termios.html#module-termios" rel="nofollow">termios</a>.</p>

<p>Here is a minimal example that waits for user input and prints the keycode if 'a' pressed ...</p>

<pre><code>    #!/usr/bin/env python

    import sys,tty
    tty.setcbreak(sys.stdin)  
    key = ord(sys.stdin.read(1))  # key captures the key-code 
    # based on the input we do something - in this case print something
    if key==97:
        print "you pressed a"
    else:
        print "you pressed something else ..."  
    sys.exit(0)
</code></pre>

<p>Hope it helps!</p>

<p><strong>Note:</strong> This solution refers to linux/mac operating systems specifically - for windows there are other ways!</p>

python osx python-2.7