根据我在互联网上发现的多种方法,我制作了以下模块。特别感谢@mishsx提供的Windows
解决方案。
使用它非常简单。您可以选择使用standby_lock
装饰器方法或通过StandbyLock
上下文管理器:
@standby_lock
def foo(*args, **kwargs):
pass
with StandbyLock():
pass
当执行 foo
时,您的系统将保持唤醒状态。
注意:仍有一些注意事项,因为Linux
可能需要sudo
特权,而OS X
(Darwin
)尚未经过测试。
from functools import wraps
import platform
class MetaStandbyLock(type):
"""
"""
SYSTEM = platform.system()
def __new__(cls, name: str, bases: tuple, attrs: dict) -> type:
if not ('inhibit' in attrs and 'release' in attrs):
raise TypeError("Missing implementations for classmethods 'inhibit(cls)' and 'release(cls)'.")
else:
if name == 'StandbyLock':
cls._superclass = super().__new__(cls, name, bases, attrs)
return cls._superclass
if cls.SYSTEM.upper() in name.upper():
if not hasattr(cls, '_superclass'):
raise ValueError("Class 'StandbyLock' must be implemented.")
cls._superclass._subclass = super().__new__(cls, name, bases, attrs)
return cls._superclass._subclass
else:
return super().__new__(cls, name, bases, attrs)
class StandbyLock(metaclass=MetaStandbyLock):
"""
"""
_subclass = None
@classmethod
def inhibit(cls):
if cls._subclass is None:
raise OSError(f"There is no 'StandbyLock' implementation for OS '{platform.system()}'.")
else:
return cls._subclass.inhibit()
@classmethod
def release(cls):
if cls._subclass is None:
raise OSError(f"There is no 'StandbyLock' implementation for OS '{platform.system()}'.")
else:
return cls._subclass.release()
def __enter__(self, *args, **kwargs):
self.inhibit()
return self
def __exit__(self, *args, **kwargs):
self.release()
class WindowsStandbyLock(StandbyLock):
"""
"""
ES_CONTINUOUS = 0x80000000
ES_SYSTEM_REQUIRED = 0x00000001
INHIBIT = ES_CONTINUOUS | ES_SYSTEM_REQUIRED
RELEASE = ES_CONTINUOUS
@classmethod
def inhibit(cls):
import ctypes
ctypes.windll.kernel32.SetThreadExecutionState(cls.INHIBIT)
@classmethod
def release(cls):
import ctypes
ctypes.windll.kernel32.SetThreadExecutionState(cls.RELEASE)
class LinuxStandbyLock(metaclass=MetaStandbyLock):
"""
"""
COMMAND = 'systemctl'
ARGS = ['sleep.target', 'suspend.target', 'hibernate.target', 'hybrid-sleep.target']
@classmethod
def inhibit(cls):
import subprocess
subprocess.run([cls.COMMAND, 'mask', *cls.ARGS])
@classmethod
def release(cls):
import subprocess
subprocess.run([cls.COMMAND, 'unmask', *cls.ARGS])
class DarwinStandbyLock(metaclass=MetaStandbyLock):
"""
"""
COMMAND = 'caffeinate'
BREAK = b'\003'
_process = None
@classmethod
def inhibit(cls):
from subprocess import Popen, PIPE
cls._process = Popen([cls.COMMAND], stdin=PIPE, stdout=PIPE)
@classmethod
def release(cls):
cls._process.stdin.write(cls.BREAK)
cls._process.stdin.flush()
cls._process.stdin.close()
cls._process.wait()
def standby_lock(callback):
""" standby_lock(callable) -> callable
This decorator guarantees that the system will not enter standby mode while 'callable' is running.
"""
@wraps(callback)
def new_callback(*args, **kwargs):
with StandbyLock():
return callback(*args, **kwargs)
return new_callback
tkinter
制作的吗?您需要提供详细信息以便其他人帮助您。 - mishsxWakeLock
或SetThreadExecutionState
或其他依赖于其运行的操作系统的内容。 - zvonestay-awake
的软件包PyPi: https://pypi.org/project/stay-awake/Github: https://github.com/singhsidhukuldeep/stay-awake 更多细节请查看答案 - Kuldeep Singh Sidhu