有没有办法从用户输入中读取一个字符?例如,他们在终端按下一个键并返回(有点像 getch()
)。我知道 Windows 中有一个功能,但我想要跨平台的功能。
原文由 Evan Fosmark 发布,翻译遵循 CC BY-SA 4.0 许可协议
有没有办法从用户输入中读取一个字符?例如,他们在终端按下一个键并返回(有点像 getch()
)。我知道 Windows 中有一个功能,但我想要跨平台的功能。
原文由 Evan Fosmark 发布,翻译遵循 CC BY-SA 4.0 许可协议
sys.stdin.read(1)
基本上会从 STDIN 读取 1 个字节。
如果您必须使用不等待 \n
的方法,您可以按照先前答案中的建议使用此代码:
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()
( 取自 http://code.activestate.com/recipes/134892/ )
原文由 Yuval Adam 发布,翻译遵循 CC BY-SA 3.0 许可协议
2 回答5.3k 阅读✓ 已解决
2 回答1.2k 阅读✓ 已解决
4 回答1.5k 阅读✓ 已解决
3 回答1.4k 阅读✓ 已解决
3 回答1.3k 阅读✓ 已解决
1 回答1.2k 阅读✓ 已解决
2 回答965 阅读✓ 已解决
下面是 ActiveState Recipes 站点的链接,其中介绍了如何在 Windows、Linux 和 OSX 中读取单个字符:
在 Windows 和 Unix 上从 stdin 读取类似 getch() 的无缓冲字符