Python3.x 实现实时读取
写在前面
参考了某篇博客,时间长了忘了
Python3.x 只有整行读取(即输入一行,回车后读入),不能实时读取(或者我没发现)
代码
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()
# 具体实现
while True:
cmd = getch()
if cmd == 'q' or cmd == 'Q':
break
print(cmd)
写在后面
Linux 和 Windwos 平台都 OK
comment:
- Valine
- LiveRe
- ChangYan