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

时间:2012-02-27 13:16:43

标签: python linux xlib

我在Python Xlib中找不到类似XGetWindowProperty的东西......

2 个答案:

答案 0 :(得分:2)

它就在文档中:

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

  

方法:Window get_property(property,type,offset,length,delete =   0)返回None或Card32('property_type'),Card8('format'),   PropertyData('value'),Card32('bytes_after'),

答案 1 :(得分:0)

使用get_property而不是使用get_full_property。它隐藏了XGetWindowProperty API的陌生方面。

我不得不通过python-xlib源代码grep来查找其用法示例,但这是我最终编写的使用它的简化版本。

this spec_NET_CLIENT_LIST的定义:

_NET_CLIENT_LIST, WINDOW[]/32

...以及this spec_NET_WM_STRUT_PARTIAL的定义:

_NET_WM_STRUT_PARTIAL, 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,CARDINAL[12]/32

...转换为以下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是由十二个32位整数组成的array.array,因为规范要求将_NET_WM_STRUT_PARTIAL设置为CARDINAL[12]/32。您可以迭代或索引{ {1}}与普通array.arraylist的方式相同,但是tuple是使用命名属性的简单,便捷的方法。)