gpt4 book ai didi

python - 如何读取用户的单个字符?

转载 作者:太空宇宙 更新时间:2023-11-03 20:22:13 26 4
gpt4 key购买 nike

有没有一种方法可以从用户输入中读取单个字符?例如,他们在终端按下一个键,然后返回该键(有点像 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/58086399/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com