Reputation: 479
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.
Upvotes: 0
Views: 1309
Reputation: 158
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
Upvotes: 2
Reputation: 6368
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()
Upvotes: 2
Reputation: 12693
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]
Upvotes: 0