python - 如何从用户那里读取单个字符?

标签 python input

有没有办法从用户输入中读取一个字符?例如,他们在终端按下一个键并返回(有点像 getch())。我知道 Windows 中有一个功能,但我想要跨平台的功能。

最佳答案

这是 ActiveState Recipes 站点的链接,其中介绍了如何在 Windows、Linux 和 OSX 中读取单个字符:

getch()-like unbuffered character reading from stdin on both Windows and Unix

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()

关于python - 如何从用户那里读取单个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47523196/

相关文章:

python - 如何在 Python matplotlib 中正确缩放 3d Quiver 图?

python - Big Query 如何更改列模式?

python - 使用 python 控制应用程序

c++ - 检查用户输入是否输入了重复的数字

javascript - 使用 Javascript (JQuery) 防止文件输入发生更改

python - 将 GAE 的搜索 API 与 ndb 的 tasklet 结合使用

python - Python 3.4 中的多处理被破坏了吗?

input - 在 z/OS Assembler 中,我可以读取 JCL 输入流两次吗?

javascript - 根据在输入框中输入相同的数字来阻止表单提交

java - 使用java中的输入/输出程序计算单词的出现次数