从python中的xinput测试读取stdout

2024-05-16 01:51:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将xinput的输出流式传输到python程序中,但是我的程序只是等待并保持空白。我想这可能和缓冲有关,但我不能说。运行xinput test 15可以让我移动鼠标,但这样做不会打印出来。顺便说一句,要找到你的mouseid,只要输入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()    

Tags: testimport程序binusrstdoutsysline
2条回答

您的代码适合我;但是如果没有连接到tty,xinputcmd会缓冲其输出。在运行代码时,继续移动鼠标,最终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

看看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)

相关问题 更多 >