You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Python扩展TinyWM:将TinyWM的C语言快捷键绑定代码迁移至Python实现

Convert TinyWM's Mod4+F1 Keybind to Python

Got it, let's turn that TinyWM C keybinding logic into Python! We'll use the python-xlib library to interact directly with X11, just like the C code does. Here's a step-by-step breakdown:

Step 1: Install Dependencies

First, install the required X11 bindings for Python:

pip install python-xlib

Step 2: Python Implementation

This code mirrors the C snippet's functionality, with Pythonic improvements (like using subprocess instead of system for safer process management):

from Xlib import X, display
import subprocess

def main():
    # Initialize X11 display (equivalent to XOpenDisplay in C)
    dsp = display.Display()
    root_window = dsp.screen().root

    # Get F1 keycode (equivalent to XKeysymToKeycode + XStringToKeysym)
    f1_keysym = X.string_to_keysym("F1")
    f1_keycode = dsp.keysym_to_keycode(f1_keysym)

    # Grab Mod4 + F1 (equivalent to XGrabKey)
    dsp.grab_key(
        f1_keycode,
        X.Mod4Mask,
        root_window,
        owner_events=True,
        pointer_mode=X.GrabModeAsync,
        keyboard_mode=X.GrabModeAsync
    )

    # Event loop (equivalent to XNextEvent loop)
    while True:
        ev = dsp.next_event()
        if ev.type == X.KeyPress:
            # Check if the pressed key is F1 (fixes a typo in your C code: ev.xkey, not ev.xbutton)
            if ev.xkey.keycode == f1_keycode:
                # Launch xterm (safer alternative to system())
                subprocess.Popen(
                    ["xterm"],
                    stdout=subprocess.DEVNULL,
                    stderr=subprocess.DEVNULL
                )

if __name__ == "__main__":
    main()

Key Notes & Comparisons to the C Code

  • Display Initialization: display.Display() replaces XOpenDisplay in C, handling the connection to the X server.
  • Key Grabbing: dsp.grab_key() maps directly to XGrabKey, with parameters matching the C code's behavior (async grab modes, owning events).
  • Event Handling: The while True loop with dsp.next_event() replicates the XNextEvent loop. We use ev.xkey.keycode instead of ev.xbutton.button (your original C code had a small typo here—KeyPress events use the xkey struct, not xbutton).
  • Launching Xterm: We use subprocess.Popen instead of system() because it's more secure and avoids blocking the event loop. The DEVNULL redirects output so xterm doesn't clutter your terminal.

How to Use

Run the script, then press Mod4 (Windows/Super key) + F1—xterm should launch just like in the TinyWM C code.

内容的提问来源于stack exchange,提问作者xxx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 20:47:42