# import sys, os
def wait_key():
''' Wait for a key press on the console and return it. '''
result = None
if os.name == 'nt':
import msvcrt
result = msvcrt.getch()
else:
import termios
fd = sys.stdin.fileno()
oldterm = termios.tcgetattr(fd)
newattr = termios.tcgetattr(fd)
newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
termios.tcsetattr(fd, termios.TCSANOW, newattr)
try:
result = sys.stdin.read(1)
except IOError:
pass
finally:
termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
return result
I removed the fctl/non-blocking stuff because it was giving IOErrors and I didn't need it. I'm using this code specifically because I want it to block. ;)
This only waits for a user to press enter though, so you might want to use msvcrt ((Windows/DOS only) The msvcrt module gives you access to a number of functions in the Microsoft Visual C/C++ Runtime Library (MSVCRT)):
If you want to see if they pressed a exact key (like say 'b') Do this:
Cross Platform, Python 2/3 code:
I removed the fctl/non-blocking stuff because it was giving
IOError
s and I didn't need it. I'm using this code specifically because I want it to block. ;)One way to do this in Python 2, is to use
raw_input()
:In python3 it's just
input()
In Python 3, no
raw_input()
exists. So, just use:This only waits for a user to press enter though, so you might want to use msvcrt ((Windows/DOS only) The msvcrt module gives you access to a number of functions in the Microsoft Visual C/C++ Runtime Library (MSVCRT)):
This should wait for a key press.
If you are ok with depending on system commands you can use the following:
Linux:
Windows:
If you want to wait for enter (so the user knocking the keyboard does not cause something un-intended to happen) use