通过 Python3 在 Mac 上检测锁定屏幕

Detecting lock screen on Mac through Python3

尝试找到一种方法来检测屏幕是否在 Mac 系统上被锁定,使用 Python3

我已经尝试了以下方法,它给出了一个 KeyError:

import Quartz
gui_dict = Quartz.CGSessionCopyCurrentDictionary()
print(gui_dict['CGSSessionScreenIsLocked'])

编辑:

import Quartz
all_windows = Quartz.CGWindowListCopyWindowInfo(Quartz.kCGWindowListOptionOnScreenOnly, Quartz.kCGNullWindowID)
for x in all_windows:
    if x["kCGWindowOwnerName"] == "loginwindow"
        print("Locked!")

此代码适用于 Python2,但考虑到需要使用 /usr/bin/python 导入 Quartz,因此不适用于 3。

安装quartz-
pip install pyobjc-framework-Quartz

很多简单的代码 -

import Quartz
d = Quartz.CGSessionCopyCurrentDictionary()
print('CGSSessionScreenIsLocked' in d.keys())