<p>请参阅<a href="http://docs.python.org/library/tty.html" rel="nofollow noreferrer">tty</a>标准模块。它允许使用<a href="http://docs.python.org/library/tty.html#tty.setcbreak" rel="nofollow noreferrer">tty.setcbreak(sys.stdin)</a>从默认的面向行(cooke)模式切换到面向字符(cbreak)模式。从sys.stdin读取单个字符将导致下一个按下的键盘键(如果它生成代码):</p>
<pre><code>import sys
import tty
tty.setcbreak(sys.stdin)
while True:
print ord(sys.stdin.read(1))
</code></pre>
<p><em>注意:解决方案仅限于Unix(包括Linux)。</em></p>
<p>编辑:在Windows上尝试<a href="http://docs.python.org/library/msvcrt.html#msvcrt.getche" rel="nofollow noreferrer">msvcrt.getche()</a>/<a href="http://docs.python.org/library/msvcrt.html#msvcrt.getwche" rel="nofollow noreferrer">getwche()</a>。/我无处可去。。。</p>
<hr/>
<p>编辑2:通过<a href="http://docs.python.org/library/ctypes.html" rel="nofollow noreferrer">ctypes.windll</a>(请参阅<a href="https://stackoverflow.com/questions/239020/how-can-i-call-a-dll-from-a-scripting-language">example at SO</a>)和<code>ReadConsoleInput</code>函数利用win32低级控制台API。你应该过滤掉按键-<code>e.EventType==KEY_EVENT</code>并寻找<code>e.Event.KeyEvent.wVirtualKeyCode</code>值。可以在<a href="http://www.benryves.com/tutorials/?t=winconsole&c=4" rel="nofollow noreferrer">http://www.benryves.com/tutorials/?t=winconsole&c=4</a>找到应用程序的示例(不是在Python中,只是为了得到一个想法)。</p>