Home > Backend Development > Python Tutorial > How Can I Read a Single Character from User Input Cross-Platform?

How Can I Read a Single Character from User Input Cross-Platform?

Susan Sarandon
Release: 2024-12-21 05:10:15
Original
991 people have browsed it

How Can I Read a Single Character from User Input Cross-Platform?

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:

    • Import the msvcrt module and use msvcrt.getch().
  • Linux and OSX:

    • Set the standard input to raw mode using tty.setraw() to disable buffering.
    • Read a single character using sys.stdin.read(1).
    • Restore the original settings after reading the character.

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()
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template