从python中的xinput测试中读取stdout

时间:2012-09-14 08:47:35

标签: python linux input pipe xorg

我正在尝试将xinput的输出流式传输到我的python程序中,但是我的程序只是等待并保持空白。我认为它可能与缓冲有关,但我不能说。运行xinput test 15给我的鼠标移动,但这样做不会打印它。顺便说一下,要找出你的鼠标,只需输入xinput,它就会列出你的设备。

#!/usr/bin/env python
import sys
import subprocess


# connect to mouse
g = subprocess.Popen(["xinput", "test", str(mouse_id)], stdout=subprocess.PIPE)

for line in g.stdout:
    print(line)
    sys.stdout.flush()    

2 个答案:

答案 0 :(得分:2)

您的代码适合我;但是如果没有连接到tty,xinput cmd似乎会缓冲其输出。在运行代码时,继续移动鼠标,最后xinput应该刷新stdout,你会看到你的行显示在块中......至少我在运行你的代码时做了。

我重新编写了你的​​代码以消除缓冲,但是我无法让它不是以块的形式出现,因此我认为xinput应该归咎于它。未连接到TTY时,它不会刷新每个新事件的stdout缓冲区。这可以通过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

答案 1 :(得分:1)

查看sh,特别是本教程http://amoffat.github.com/sh/tutorials/1-real_time_output.html

import sh
for line in sh.xinput("test", mouse_id, _iter=True):
    print(line)