|
发表于 2022-5-12 02:35:19
|
显示全部楼层
本楼为最佳答案
本帖最后由 hrpzcf 于 2022-5-12 02:45 编辑
那就调用系统 API,只要这个脚本不结束,系统就不会息屏和睡眠(除非被别的程序动了睡眠策略)。
time.sleep() 时间可以设置的长些,比你设置的息屏时间或者睡眠时间(两者中最小者)短几分钟就行。
- import time
- from ctypes import windll, c_uint
- KERNEL = windll.kernel32
- KERNEL.SetThreadExecutionState.restype = c_uint
- KERNEL.SetThreadExecutionState.argtypes = (c_uint,)
- RESTORE = 0x80000000
- PREVENT = 0x00000001 | 0x00000002 | 0x80000000
- def alive():
- """阻止系统息屏和睡眠"""
- return hex(KERNEL.SetThreadExecutionState(PREVENT))
- def restore():
- """恢复息屏和睡眠策略"""
- return hex(KERNEL.SetThreadExecutionState(RESTORE))
- # 调用 alive 阻止息屏睡眠,调用 restore 恢复
- # 本脚本运行后,在此脚本的控制台可以 Ctrl + C 结束运行
- try:
- print("开启状态:", alive())
- start = time.time()
- while True:
- now = time.time()
- print(f"经历时长:{now - start:.0f}")
- time.sleep(1)
- except KeyboardInterrupt:
- print("已手动恢复息屏及睡眠。")
- finally:
- print("恢复状态:", restore())
复制代码 |
|