title: How to intercept keys pressed in (and only in) the terminal window of a Python program?
body: <p>I'm writing a simple Python 3 script and I want to be able to intercept key presses inside the terminal window in order to do something depending on the returned value, for example.<br>
  I also want a cross-platform solution.</p>
  
  <p>I would like to reproduce something like this:</p>
  
  <pre class="lang-py prettyprint-override"><code>import msvcrt
  key = ord(msvcrt.getch()) # Wait for a key to be pressed.
  if key == 27: # The ESC key
      print("You have pressed the ESC key!")
  </code></pre>
  
  <p>But <code>msvcrt</code> is a Windows-specific module according to the <a href="https://docs.python.org/3/library/msvcrt.html" rel="nofollow noreferrer">Python docs</a> (and my tests):</p>
  
  <blockquote>
    <p>These functions provide access to some useful capabilities on Windows platforms.</p>
  </blockquote>
  
  <p>I've found the <a href="https://github.com/boppreh/keyboard" rel="nofollow noreferrer"><code>keyboard</code></a> module which is quite simple to use (and <em>more</em> cross-platform) but I didn't manage to "catch" only the keys pressed <strong>inside</strong> the terminal window.</p>
  
  <p>For example:</p>
  
  <pre class="lang-py prettyprint-override"><code>import keyboard as kb
  key = kb.read_hotkey()
  if key == "esc": # The ESC key
      print("You have pressed the ESC key!")
  </code></pre>
  
  <p>The code given above intercepts key presses not only when the terminal window where the script is executed is focused, but also when it is not.</p>
  
  <p>So, to conclude, do you know a pythonic way to intercept key presses inside the terminal window (and not outside) where the script is executed (something like an <em><code>input()</code> without having to press Enter</em>), and which is cross-platform (at least compatible with GNU/Linux and Windows)?</p>
  
  <p>Thank you in advance for your answers,<br>
  Regards,<br>
  Alexis.</p>