简单说一下功能和缺点
- 功能:可以实时检测输入的按键,不用按回车
- 缺点:只能在linux下运行,windows下运行会报错ModuleNotFoundError: No module named ‘termios’,
在windows上可以考虑使用wsl,子系统来运行代码,亲测有效,不过产生了一个新的小问题,ctrl+c没法停止程序了。所以写的时候可以留一个关键字用来跳出循环

上代码:
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 
 | import sysimport tty
 import termios
 
 def readchar():
 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
 
 def readkey(getchar_fn=None):
 getchar = getchar_fn or readchar
 c1 = getchar()
 if ord(c1) != 0x1b:
 return c1
 c2 = getchar()
 if ord(c2) != 0x5b:
 return c1
 c3 = getchar()
 return chr(0x10 + ord(c3) - 65)
 
 while True:
 key=readkey()
 if key=='1':
 
 
 print("保留")
 if key=='2':
 
 
 print("跳过")
 if key=='q':
 
 print("退出")
 break
 
 
 |