问题描述
我正在尝试将xinput的输出流式传输到我的python程序中,但是我的程序只是等待并保持空白.我认为这可能与缓冲有关,但是我不能说.运行xinput test 15
可以使我移动鼠标,但是这样做不会打印出来.顺便说一句,要找到您的Mouseid,只需键入xinput
,它将列出您的设备.
I am trying to stream the output of xinput into my python program, however my program just waits and stays blank. I think it may have something to do with buffering but I cannot say. Running xinput test 15
gives me my mouse movements, but doing this will not print it. By the way, to find out your mouseid just type xinput
and it will list your devices.
#!/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()
推荐答案
您的代码对我有用;但是,如果未连接到tty,则看起来xinput
cmd会缓冲其输出.在运行代码时,继续移动鼠标,最终xinput
应该刷新标准输出,并且您会看到代码行成块出现……至少我在运行代码时确实如此.
Your code works for me; however it looks like the xinput
cmd buffers its output if not connected to a tty. When running your code, keep moving the mouse and eventually xinput
should flush stdout and you'll see your lines show up in chunks... at least i did when running your code.
我重新编写了您的代码以消除缓冲,但是我无法理解它不能成块出现,因此为什么我相信xinput
是要怪的.当未连接到TTY时,它不会使用每个新事件刷新stdout缓冲区.可以使用xinput test 15 | cat
进行验证.移动鼠标将导致数据以缓冲块的形式打印;就像您的代码一样.
I re-wrote your code to eliminate buffering, but I couldn't get it to not come out in chunks, hence why I believe xinput
is to blame. When not connected to a TTY, it doesn't flush the stdout buffer with each new event. This can be verified with xinput test 15 | cat
. Moving your mouse will cause the data to print in buffered chunks; just like your code.
如果有帮助,下面是我的测试代码
My test code is below if helpful
#!/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
这篇关于从python中的xinput测试中读取stdout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!