0

我有以下代码来检查屏幕是否被锁定(使用 gnome-screensaver)

gnome-screensaver-command -q | grep "is active"

在此链接中,https://askubuntu.com/questions/17679/how-can-i-put-the-display-to-sleep-on-screen-lock有一个关于在 shell 脚本上使用它的代码。但是如何在 python 中使用代码呢?并将其存储在一个变量中,无论它是否处于活动状态。

4

3 回答 3

2

你也可以通过D-Bus与 gnome-screensaver 对话:

import dbus

def screensaver_active():
    bus = dbus.SessionBus()
    screensaver = bus.get_object('org.gnome.ScreenSaver', '/')
    return bool(screensaver.GetActive())

variable = screensaver_active()
于 2013-07-31T21:29:20.540 回答
2
import dbus

def screensaver_status():
    session_bus = dbus.SessionBus()
    screensaver_list = ['org.gnome.ScreenSaver',
                        'org.cinnamon.ScreenSaver',
                        'org.kde.screensaver',
                        'org.freedesktop.ScreenSaver']
    for each in screensaver_list:
        try:
            object_path = '/{0}'.format(each.replace('.', '/'))
            get_object = session_bus.get_object(each, object_path)
            get_interface = dbus.Interface(get_object, each)
            return bool(get_interface.GetActive())
        except dbus.exceptions.DBusException:
            pass

status = screensaver_status()
print(status)

这会捕获所有屏幕保护程序,而不仅仅是 Gnome。它也不会通过使用类似的东西来阻止

*-screensaver-command
于 2018-10-12T05:18:42.783 回答
0

您可以使用 Python 在 Python 中执行 shell 命令subprocess,然后 grep 它的 stdout for is activeline:

def isScreenLocked():
    import subprocess
    com = subprocess.Popen(['gnome-screensaver-command', '-q'], stdout = subprocess.PIPE, stderr = subprocess.PIPE)
    return "is active" in com.communicate()[0]
于 2013-04-08T06:16:29.330 回答