Use gnome-screensaver-command on python

纵饮孤独 提交于 2019-12-12 03:53:23

问题


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.


回答1:


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()



回答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)

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

*-screensaver-command



回答3:


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]


来源:https://stackoverflow.com/questions/15870493/use-gnome-screensaver-command-on-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!