获得Linux上的鼠标位置,纯Python

时间:2016-02-01 17:46:48

标签: python linux mouse x11

我正在尝试使用纯Python(如果需要,+ cyptes)在Linux中获取全局鼠标位置(x, y)。我可以通过听/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

等效代码在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;
}

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

1 个答案:

答案 0 :(得分:3)

以下适用于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

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

from Xlib import display
qp = display.Display().screen().root.query_pointer()
print qp.root_x, qp.root_y