我希望能够使用Python处理控制台中的键盘事件。正在运行的脚本有一些持久的输出流,当管理员触发按键事件时,脚本将更改其输出内容。
我已经使用以下代码完成了它(按下“q”将触发输出更改),但存在两个问题:
1. 输出中增加了一个空格。经过调试,我发现代码“tty.setraw(fd)”导致了这个问题,但我不知道如何解决它。 2. ctrl+c无法再起作用(如果# "tty.setraw(fd)",ctrl+c将起作用)。
如果这太复杂了,是否还有其他模块可以实现我的需求?我尝试了curse模块,但似乎会冻结窗口输出,并且不能在多线程中协调。
我已经使用以下代码完成了它(按下“q”将触发输出更改),但存在两个问题:
1. 输出中增加了一个空格。经过调试,我发现代码“tty.setraw(fd)”导致了这个问题,但我不知道如何解决它。 2. ctrl+c无法再起作用(如果# "tty.setraw(fd)",ctrl+c将起作用)。
如果这太复杂了,是否还有其他模块可以实现我的需求?我尝试了curse模块,但似乎会冻结窗口输出,并且不能在多线程中协调。
#!/usr/bin/python
import sys
import select
import tty, termios
import threading
import time
def loop():
while loop_bool:
if switch:
output = 'aaaa'
else:
output = 'bbbb'
print output
time.sleep(0.2)
def change():
global switch
global loop_bool
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
while loop_bool:
tty.setraw(fd)
i,o,e = select.select([sys.stdin],[],[],1)
if len(i)!=0:
if i[0] == sys.stdin:
input = sys.stdin.read(1)
if input =='q':
if switch:
switch = False
else:
switch = True
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
except KeyboardInterrupt:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
loop_bool = False
try:
switch = True
loop_bool = True
t1=threading.Thread(target=loop)
t2=threading.Thread(target=change)
t1.start()
t2.start()
t1.join(1)
t2.join(1)
except KeyboardInterrupt:
loop_bool = False
setraw
,但只在最后恢复旧设置呢? - abarnert