在Python中使用GNOME屏保命令(Use gnome-screensaver-command

2019-10-29 07:35发布

我有以下代码检查屏幕是否被锁定或没有(使用GNOME屏保)

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? 并将其存储在一个varaiable无论是否处于活动状态。

Answer 1:

你还可以说说通过在gnome屏保d总线 :

import dbus

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

variable = screensaver_active()


Answer 2:

进口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)

这捕获所有的屏保,不只是侏儒。 它也没有使用像块

*-screensaver-command


Answer 3:

您可以通过执行在Python shell命令subprocess ,然后用grep标准输出为is active行:

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


文章来源: Use gnome-screensaver-command on python