python输入单个字符_Python从用户读取单个字符

繁花如伊
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 chclass _GetchWindows:
def __init__(self):
import msvcrt def __call__(self):
import msvcrt return msvcrt.getch()getch = _Getch()(摘自 http://code.activestate.com/recipes/134892/)
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)