You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Python代码按需控制Mac屏幕调光与锁定的启停?

在Python中控制Mac屏幕变暗与锁定的特定阶段开关

当然可以实现你的需求!不用依赖全局生效的caffinate,我们可以通过Python在代码的特定阶段精准禁用屏幕调光和锁定,完成后再恢复系统原有设置。下面给你两个实用方案:

方案一:通过AppleScript调用系统设置(简单易上手)

这个方案利用Mac自带的AppleScript来读取和修改系统节能设置,不需要额外安装第三方库,用Python的subprocess模块就能调用。

代码示例

import subprocess
import time

def get_current_settings():
    # 获取当前自动锁定时间(分钟)
    lock_time = subprocess.check_output([
        "osascript", "-e", 'tell application "System Events" to get delay interval of screen saver preferences'
    ]).decode().strip()
    # 获取是否开启自动调光
    auto_dim = subprocess.check_output([
        "osascript", "-e", 'tell application "System Events" to get automatic dimmer of screen saver preferences'
    ]).decode().strip() == "true"
    return int(lock_time), auto_dim

def disable_screen_sleep():
    # 设置自动锁定为永不(0代表永不)
    subprocess.run([
        "osascript", "-e", 'tell application "System Events" to set delay interval of screen saver preferences to 0'
    ])
    # 关闭自动调光
    subprocess.run([
        "osascript", "-e", 'tell application "System Events" to set automatic dimmer of screen saver preferences to false'
    ])

def restore_screen_settings(original_lock_time, original_auto_dim):
    # 恢复原来的自动锁定时间
    subprocess.run([
        "osascript", "-e", f'tell application "System Events" to set delay interval of screen saver preferences to {original_lock_time}'
    ])
    # 恢复自动调光设置
    dim_cmd = "true" if original_auto_dim else "false"
    subprocess.run([
        "osascript", "-e", f'tell application "System Events" to set automatic dimmer of screen saver preferences to {dim_cmd}'
    ])

# 示例用法
if __name__ == "__main__":
    # 先保存当前系统设置
    original_lock, original_dim = get_current_settings()
    try:
        print("开始禁用屏幕变暗与锁定...")
        disable_screen_sleep()
        # 这里是你需要保持屏幕唤醒的代码逻辑
        time.sleep(30)  # 模拟任务运行30秒
        print("任务完成,恢复系统设置...")
    finally:
        # 不管代码是否报错,都要恢复原始设置
        restore_screen_settings(original_lock, original_dim)

注意事项

  • 首次运行可能会弹出权限请求,需要在系统偏好设置 > 安全性与隐私 > 隐私 > 辅助功能中,勾选你的Python解释器或终端程序,赋予它控制系统设置的权限。

方案二:使用原生Quartz API(更精细控制)

这个方案通过PyObjC绑定调用Mac的Quartz框架API,和caffinate工具底层用的是同一套系统接口,控制更精准,不会修改全局的节能设置(只是创建一个临时的唤醒断言)。

步骤1:安装依赖

首先需要安装PyObjC的Quartz框架绑定:

pip install pyobjc-framework-Quartz

代码示例

import Quartz
import time

class ScreenWakeLock:
    def __enter__(self):
        # 创建唤醒断言,阻止屏幕睡眠和系统睡眠
        self.assertion_id = Quartz.IOPMAssertionCreateWithName(
            Quartz.kIOPMAssertionTypeNoDisplaySleep,
            Quartz.kIOPMAssertionLevelOn,
            None,
            None
        )
        if self.assertion_id == 0:
            raise RuntimeError("无法创建屏幕唤醒断言,请检查权限")
        print("屏幕唤醒断言已创建,屏幕将保持亮着")
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        # 释放唤醒断言,恢复正常
        if self.assertion_id != 0:
            Quartz.IOPMAssertionRelease(self.assertion_id)
            print("屏幕唤醒断言已释放,恢复正常屏幕设置")

# 示例用法
if __name__ == "__main__":
    with ScreenWakeLock():
        # 这里是需要保持屏幕唤醒的代码阶段
        time.sleep(30)  # 模拟任务运行30秒
    # 离开with块后,自动恢复正常

优势说明

  • 这个方案不会修改系统的全局节能设置,只是在代码运行的特定阶段创建一个临时的“唤醒断言”,结束后自动释放,更安全。
  • 不需要修改系统偏好设置的权限(部分情况下可能需要授予终端/程序“节能设置”权限,但比方案一的权限要求更宽松)。

两种方案都能满足你的需求,如果你追求简单快捷,选方案一;如果想要更原生、不修改系统设置的精细控制,选方案二。

内容的提问来源于stack exchange,提问作者ToniE

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:23:16