【问题标题】:Reading stdout from xinput test in python从 python 中的 xinput 测试中读取标准输出
【发布时间】:2012-09-14 08:47:34
【问题描述】:

我正在尝试将 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()    

【问题讨论】:

  • 输出中是否有换行符?如果您在一段时间后终止子进程会发生什么?冲洗g.stdout有效果吗?
  • xinput test 为每个事件返回一个新行,而对于终止它只会给键盘中断 啊哈,我认为您对g.stdout.flush() 的更改产生了影响。它现在输出,哇!
  • 现在唯一的问题是刷新需要几秒钟,这意味着为了进行测试,我必须获取数百甚至数千行,直到它们全部转储。无论如何,只要我能得到它就强制立即转储(从控制台运行命令时没有延迟)

标签: python linux input pipe xorg


【解决方案1】:

您的代码对我有用;但是,如果未连接到 tty,它看起来像 xinput 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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-05
      • 2012-04-25
      • 2011-10-21
      相关资源
      最近更新 更多