gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:27:24 35 4
gpt4 key购买 nike

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

最佳答案

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

我必须 grep 遍历 python-xlib 源代码才能找到它的使用示例,但这里是我最终编写的使用它的简化版本。

_NET_CLIENT_LIST 的定义来自 this spec :

_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 是 12 个 32 位整数的 array.array,因为规范要求将 _NET_WM_STRUT_PARTIAL 设置为CARDINAL[12]/32。您可以像处理普通 listtuple 一样迭代或索引 array.array ,但是 namedtuple 是一种使用命名属性的简单、舒适的方式。)

关于python - 如何使用 python-xlib 读取 X 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9465651/

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