我有以下代码来检查屏幕是否被锁定(使用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中使用代码?无论是否有效,都可以存储它。
答案 0 :(得分: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()
答案 1 :(得分:1)
导入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
答案 2 :(得分:0)
您可以使用subprocess
在Python中执行shell命令,然后为is active
行grep其stdout:
def isScreenLocked():
import subprocess
com = subprocess.Popen(['gnome-screensaver-command', '-q'], stdout = subprocess.PIPE, stderr = subprocess.PIPE)
return "is active" in com.communicate()[0]