使用 Python 禁止屏幕保护程序

ov1*_*d1u 6 python linux screensaver xorg

在 Linux 中禁用屏幕保护程序的更好的跨 DE 方法是什么?我在这里找到了一些东西,但它仅适用于 gnome-screensaver。我想知道是否有任何方法可以模拟击键或某些 X.Org API 来禁用屏幕保护程序激活。

ccp*_*zza 5

我不久前一直在研究这个问题,最后最终使用了xdg-screensaver我调用的 via subprocess

import subprocess

def suspend_screensaver():
    window_id = subprocess.Popen('xwininfo -root | grep xwininfo | cut -d" " -f4', stdout=subprocess.PIPE, shell=True).stdout.read().strip()

    #run xdg-screensaver on root window
    subprocess.call(['xdg-screensaver', 'suspend', window_id])

def resume_screensaver(window_id):
    subprocess.Popen('xdg-screensaver resume ' + window_id, shell=True)
Run Code Online (Sandbox Code Playgroud)

这并不理想,但显然没有其他解决方案不会涉及到使用 DE 特定的东西,例如dbusgnome-screensaver-command

我真的不喜欢这个电话xwininfo,希望有一个更干净的方法,但到目前为止找不到更好的方法。该xwininfo方法的另一个问题是它使用根窗口的 ID 而不是应用程序窗口。使用应用程序窗口 ID 而不是根窗口将消除对该resume_screensaver方法的需要,因为一旦窗口被销毁,它就会恢复。

如果你想模拟击键,这里有一个我已经使用了一段时间的简单的 bash 脚本。它确实要求xdotool必须单独安装。

#!/bin/bash
while : 
do
   sleep 200
   nice -n 1 xdotool key shift
   echo .
done
Run Code Online (Sandbox Code Playgroud)

更新

使用上面的 python 解决方案一年多后,发现偶尔会创建僵尸进程和/或太多实例xdg-screensaver,因此在深入研究后,我找到了一个更简单的替代方案,它是Gnome 特定的,但即使在非 Gnome DE (XFCE),因为即使您没有 Gnome 桌面,许多基于 GTK 的应用程序也需要核心 Gnome 库。

import subprocess

def suspend_screensaver():
    'suspend linux screensaver'
    proc = subprocess.Popen('gsettings set org.gnome.desktop.screensaver idle-activation-enabled false', shell=True)
    proc.wait()

def resume_screensaver():
    'resume linux screensaver'
    proc = subprocess.Popen('gsettings set org.gnome.desktop.screensaver idle-activation-enabled true', shell=True)
    proc.wait()
Run Code Online (Sandbox Code Playgroud)