Getting a Single Character Input Cross-Platform
Reading a single character from the user's input is useful in various scenarios. To achieve this, you can utilize the following cross-platform solution:
The ActiveState Recipes site provides a comprehensive recipe that targets different operating systems:
Windows:
Linux and OSX:
The provided code snippet illustrates this implementation:
class _Getch: def __init__(self): try: self.impl = _GetchWindows() except ImportError: self.impl = _GetchUnix() def __call__(self): return self.impl() class _GetchUnix: def __init__(self): import tty, sys def __call__(self): import sys, tty, termios fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch class _GetchWindows: def __init__(self): import msvcrt def __call__(self): import msvcrt return msvcrt.getch() getch = _Getch()
Simply calling getch() will get you a single character without any buffering or echoing to the terminal.
The above is the detailed content of How Can I Read a Single Character from User Input Cross-Platform?. For more information, please follow other related articles on the PHP Chinese website!