你的代码对我有用;xinput
但是,如果未连接到 tty,cmd似乎会缓冲其输出。运行代码时,继续移动鼠标,最终xinput
应该刷新标准输出,你会看到你的行以块的形式出现......至少我在运行你的代码时做到了。
我重新编写了您的代码以消除缓冲,但我无法让它不成块出现,因此我认为这xinput
是罪魁祸首。当未连接到 TTY 时,它不会用每个新事件刷新标准输出缓冲区。这可以用 来验证xinput test 15 | cat
。移动鼠标将导致数据以缓冲块的形式打印;就像你的代码一样。
如果有帮助,我的测试代码如下
#!/usr/bin/python -u
# the -u flag makes python not buffer stdios
import os
from subprocess import Popen
_read, _write = os.pipe()
# I tried os.fork() to see if buffering was happening
# in subprocess, but it isn't
#if not os.fork():
# os.close(_read)
# os.close(1) # stdout
# os.dup2(_write, 1)
#
# os.execlp('xinput', 'xinput', 'test', '11')
# os._exit(0) # Should never get eval'd
write_fd = os.fdopen(_write, 'w', 0)
proc = Popen(['xinput', 'test', '11'], stdout = write_fd)
os.close(_write)
# when using os.read() there is no readline method
# i made a generator
def read_line():
line = []
while True:
c = os.read(_read, 1)
if not c: raise StopIteration
if c == '\n':
yield "".join(line)
line = []
continue
line += c
readline = read_line()
for each in readline:
print each