Home >Backend Development >Python Tutorial >How to Read a Single Character from User Input Across Different Platforms?
Reading a Single Character from User Input Cross-Platform
In various programming scenarios, it becomes necessary to read a single character from user input without buffering or echoing. This functionality is similar to the renowned getch() function available in Windows, but a universal approach that works across multiple platforms is desired.
Solution:
To achieve this cross-platform character reading, you can utilize a community-driven Python recipe from the ActiveState Recipes site: "getch()-like unbuffered character reading from stdin on both Windows and Unix." This recipe provides a class-based implementation, catering to both Windows and Unix-based systems.
Implementation:
The following code snippet demonstrates the implementation of the cross-platform character reading class:
class _Getch: """Gets a single character from standard input. Does not echo to the screen.""" 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()
To utilize this class, simply instantiate the _Getch class and call it. The result will be the single character typed by the user, without any buffering or echoing. For instance:
result = getch()
Conclusion:
This cross-platform character reading approach is widely applicable in situations where immediate user input is required, such as capturing keystrokes in terminal applications or implementing interactive user interfaces.
The above is the detailed content of How to Read a Single Character from User Input Across Different Platforms?. For more information, please follow other related articles on the PHP Chinese website!