gpt4 book ai didi

python - 从 python 中的 xinput 测试读取标准输出

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:58:27 26 4
gpt4 key购买 nike

我试图将 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()

最佳答案

你的代码对我有用;但是,如果未连接到 tty,xinput cmd 似乎会缓冲其输出。运行您的代码时,继续移动鼠标,最终 xinput 应该会刷新 stdout,您会看到您的行以 block 的形式出现……至少我在运行您的代码时是这样的。

我重新编写了您的代码以消除缓冲,但我无法让它不分块出现,因此我认为应该归咎于 xinput。当未连接到 TTY 时,它不会使用每个新事件刷新标准输出缓冲区。这可以通过 xinput test 15 | 验证猫。移动鼠标将导致数据以缓冲 block 的形式打印;就像您的代码一样。

如果有帮助,下面是我的测试代码

#!/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 - 从 python 中的 xinput 测试读取标准输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12420999/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com