有没有一种方法可以在Python脚本内防止运行OS X的计算机进入睡眠状态?
您可以使用内置的caffeinate命令。
subprocess.Popen('caffeinate')
这是我使用它的方法:
import sys
import subprocess
if 'darwin' in sys.platform:
print('Running \'caffeinate\' on MacOSX to prevent the system from sleeping')
subprocess.Popen('caffeinate')
你还可以在外部终端窗口中运行caffeinate
并保持其打开,以实现OP想要的功能。
打开终端
键入caffeinate
按下Enter
这样做后,你的Mac将保持清醒状态,直到你关闭该终端。
你可以将其最小化或隐藏,你的Mac将不会进入睡眠模式,直到你使用键盘快捷键Ctrl+C来中断命令。
有一个Python实用程序,演示了如何直接在Python中引发所需的断言:https://github.com/minrk/appnope
python <location/of/my/script.py> <hour until I want the PC to be awake>
e.g.
python /Users/johndee/Downloads/keep_awake.py 18:30
要保存在本地的脚本:
#!/usr/bin/env python3
import random
import sys
import time
from datetime import datetime
from tkinter import Tk
import pyautogui
CHECK_STATUS_ONCE_IN = 120
WAIT_FOR_POSITION_CHANGE = 10
def current_position():
tkinter = Tk()
return [tkinter.winfo_pointerx(), tkinter.winfo_pointery()]
def mouse_is_moving():
pos1 = current_position()
time.sleep(WAIT_FOR_POSITION_CHANGE)
pos2 = current_position()
return not pos1 == pos2
def keep_awake():
# Shake the mouse a lil bit
initial_x, initial_y = current_position()
try:
for _ in range(random.randint(1, 10)):
# Mouse
pyautogui.moveTo(random.randint(1, 1000), random.randint(1, 1000))
# Keys
pyautogui.press("shift")
# Restore controls
pyautogui.moveTo(initial_x, initial_y)
except pyautogui.FailSafeException as e:
print(e)
def inspect_activity_until(time_to_stop: datetime):
time_to_stop = datetime.now().replace(
hour=time_to_stop.hour, minute=time_to_stop.minute
)
while datetime.now() < time_to_stop:
if not mouse_is_moving():
keep_awake()
time.sleep(CHECK_STATUS_ONCE_IN)
print(f"Stopping at {datetime.now()}")
if __name__ == "__main__":
given_time = sys.argv[1]
date_time_obj = datetime.strptime(given_time, "%H:%M")
inspect_activity_until(date_time_obj)