如何使用python-xlib读取X属性?

2024-09-27 00:12:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我在pythonxlib中找不到类似XGetWindowProperty的东西。。。在


Tags: pythonxlibxgetwindowproperty
2条回答

不要使用get_property,而是使用get_full_property。它隐藏了XGetWindowProperty的API的奇怪方面。在

我不得不浏览pythonxlib源代码以找到它的使用示例,但下面是我最后编写的一个简化版本,以使用它。在

来自this spec_NET_CLIENT_LIST的定义:

_NET_CLIENT_LIST, WINDOW[]/32

…以及来自this spec_NET_WM_STRUT_PARTIAL的定义:

^{pr2}$

…转换为以下Python代码:

from collections import namedtuple

from Xlib.display import Display
from Xlib import Xatom

display = Display()
root = display.screen(0)['root']

StrutPartial = namedtuple('StrutPartial', 'left right top bottom'
    ' left_start_y left_end_y right_start_y right_end_y'
    ' top_start_x, top_end_x, bottom_start_x bottom_end_x')


def query_property(win, name, prop_type, format_size, empty=None):
    if isinstance(win, int):
        # Create a Window object for the Window ID
        win = display.create_resource_object('window', win)
    if isinstance(name, str):
        # Create/retrieve the X11 Atom for the property name
        name = display.get_atom(name)

    result = win.get_full_property(name, prop_type)
    if result and result.format == format_size:
        return result.value
    return empty

window_ids = ([root.id] +
    list(query_property(root, '_NET_CLIENT_LIST', Xatom.WINDOW, 32, [])))

for wid in window_ids:
    result = query_property(wid, '_NET_WM_STRUT_PARTIAL', Xatom.CARDINAL, 32)

    if result:
        # Toss it in a namedtuple to avoid needing opaque numeric indexes
        strut = StrutPartial(*result)
        print(strut)

…打印此示例输出:

StrutPartial(left=0, right=0, top=0, bottom=30, left_start_y=0, left_end_y=0, right_start_y=0, right_end_y=0, top_start_x=0, top_end_x=0, bottom_start_x=3200, bottom_end_x=4479)
StrutPartial(left=0, right=0, top=0, bottom=30, left_start_y=0, left_end_y=0, right_start_y=0, right_end_y=0, top_start_x=0, top_end_x=0, bottom_start_x=1280, bottom_end_x=3199)
StrutPartial(left=0, right=0, top=0, bottom=0, left_start_y=0, left_end_y=0, right_start_y=0, right_end_y=0, top_start_x=0, top_end_x=0, bottom_start_x=0, bottom_end_x=0)
StrutPartial(left=0, right=0, top=0, bottom=30, left_start_y=0, left_end_y=0, right_start_y=0, right_end_y=0, top_start_x=0, top_end_x=0, bottom_start_x=0, bottom_end_x=1279)

result.value是12个32位整数的array.array,因为规范要求将_NET_WM_STRUT_PARTIAL设置为CARDINAL[12]/32。您可以迭代或索引array.array,方法与普通的list或{}相同,但是namedtuple是使用命名属性的简单、舒适的方法。)

它就在文档中:

http://python-xlib.sourceforge.net/doc/html/python-xlib_21.html#SEC20

Method: Window get_property ( property, type, offset, length, delete = 0 ) Returns None or Card32('property_type'), Card8('format'), PropertyData('value'), Card32('bytes_after'),

相关问题 更多 >

    热门问题