Use gnome-screensaver-command on python

2019-09-06 13:07发布

I have the following code to check whether the screen is locked or not (using gnome-screensaver)

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

From this link, https://askubuntu.com/questions/17679/how-can-i-put-the-display-to-sleep-on-screen-lock there is a code on using it on a shell script. But how do I use the code in python? And store it in a varaiable whether if it is active or not.

3条回答
贪生不怕死
2楼-- · 2019-09-06 13:43

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)

This catches all screensavers, not just Gnome. It also doesn't block by using something like

*-screensaver-command
查看更多
Fickle 薄情
3楼-- · 2019-09-06 13:47

You can also talk to the gnome-screensaver via D-Bus:

import dbus

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

variable = screensaver_active()
查看更多
Explosion°爆炸
4楼-- · 2019-09-06 13:59

You can execute the shell command in Python using subprocess, and then grep its stdout for is active line:

def isScreenLocked():
    import subprocess
    com = subprocess.Popen(['gnome-screensaver-command', '-q'], stdout = subprocess.PIPE, stderr = subprocess.PIPE)
    return "is active" in com.communicate()[0]
登录 后发表回答