有没有办法从用户输入中读取一个字符?例如,他们在终端按下一个键并返回(有点像 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/