在 Linux 上获取鼠标位置,纯 Python

Bop*_*reH 3 python linux x11 mouse

我正在尝试(x, y)使用纯 Python获取Linux 中的全局鼠标位置(如有必要,请使用 +ctypes)。我可以通过听来获得相对位置的变化/dev/input/mice,但我没有收到任何带有绝对位置校准(EV_ABS)的事件。

我尝试使用 ctypes 连接到 X11,但是在段错误之后的所有内容XOpenDisplay(是的,XOpenDisplay工作和返回的非零值):

import ctypes
import ctypes.util
x11 = ctypes.cdll.LoadLibrary(ctypes.util.find_library('X11'))
display = x11.XOpenDisplay(None)
assert display
window = x11.XDefaultRootWindow(display) # segfault here
Run Code Online (Sandbox Code Playgroud)

等效代码在 C 中运行良好,但我正在寻找没有依赖项或编译步骤的解决方案:

#include <stdio.h>
#include <stdlib.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>

int main (){
    Display *display = XOpenDisplay(NULL);
    XEvent event;
    XQueryPointer(display, XDefaultRootWindow(display),
        &event.xbutton.root, &event.xbutton.window,
        &event.xbutton.x_root, &event.xbutton.y_root,
        &event.xbutton.x, &event.xbutton.y,
        &event.xbutton.state);
    printf("%d %d\n", event.xbutton.x_root, event.xbutton.y_root);
    XCloseDisplay(display);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这是在 Fedora 23、64 位上测试的。

Rob*_*obᵩ 5

以下适用于我在 Ubuntu 14.04.3 上使用 Python 2.7.6。它几乎完全复制自https://unix.stackexchange.com/a/16157/4836

#! /usr/bin/env python
import sys
from ctypes import *
Xlib = CDLL("libX11.so.6")
display = Xlib.XOpenDisplay(None)
if display == 0: sys.exit(2)
w = Xlib.XRootWindow(display, c_int(0))
(root_id, child_id) = (c_uint32(), c_uint32())
(root_x, root_y, win_x, win_y) = (c_int(), c_int(), c_int(), c_int())
mask = c_uint()
ret = Xlib.XQueryPointer(display, c_uint32(w), byref(root_id), byref(child_id),
                         byref(root_x), byref(root_y),
                         byref(win_x), byref(win_y), byref(mask))
if ret == 0: sys.exit(1)
print child_id.value
print root_x, root_y
Run Code Online (Sandbox Code Playgroud)

编辑:以下脚本,使用 python-xlib 0.12,打印根窗口的鼠标位置:

from Xlib import display
qp = display.Display().screen().root.query_pointer()
print qp.root_x, qp.root_y
Run Code Online (Sandbox Code Playgroud)