Windows PC的睡眠/挂起/休眠
我想写一个简单的Python脚本,让我的电脑进入睡眠状态。我已经查过API了,但关于“挂起”的结果只和延迟执行有关。请问哪个函数可以实现这个功能呢?
6 个回答
12
我不知道怎么让电脑进入睡眠状态,但我知道怎么让它休眠(在Windows上)。也许这就够了?
shutdown.exe
是你的好帮手!可以在命令提示符下运行它。
如果想查看它的选项,可以输入:
shutdown.exe /?
我相信让电脑休眠的命令是:
shutdown.exe /h
所以,把这些放在一起用Python写:
import os
os.system("shutdown.exe /h")
不过,正如其他人提到的,使用os.system其实是不太好的做法。应该用popen来代替。不过,如果你和我一样懒,只是写个小脚本,那就随便吧!我还是用os.system。
6
如果不使用命令行执行,你可以利用pywin32和ctypes这两个库:
import ctypes
import win32api
import win32security
def suspend(hibernate=False):
"""Puts Windows to Suspend/Sleep/Standby or Hibernate.
Parameters
----------
hibernate: bool, default False
If False (default), system will enter Suspend/Sleep/Standby state.
If True, system will Hibernate, but only if Hibernate is enabled in the
system settings. If it's not, system will Sleep.
Example:
--------
>>> suspend()
"""
# Enable the SeShutdown privilege (which must be present in your
# token in the first place)
priv_flags = (win32security.TOKEN_ADJUST_PRIVILEGES |
win32security.TOKEN_QUERY)
hToken = win32security.OpenProcessToken(
win32api.GetCurrentProcess(),
priv_flags
)
priv_id = win32security.LookupPrivilegeValue(
None,
win32security.SE_SHUTDOWN_NAME
)
old_privs = win32security.AdjustTokenPrivileges(
hToken,
0,
[(priv_id, win32security.SE_PRIVILEGE_ENABLED)]
)
if (win32api.GetPwrCapabilities()['HiberFilePresent'] == False and
hibernate == True):
import warnings
warnings.warn("Hibernate isn't available. Suspending.")
try:
ctypes.windll.powrprof.SetSuspendState(not hibernate, True, False)
except:
# True=> Standby; False=> Hibernate
# https://msdn.microsoft.com/pt-br/library/windows/desktop/aa373206(v=vs.85).aspx
# says the second parameter has no effect.
# ctypes.windll.kernel32.SetSystemPowerState(not hibernate, True)
win32api.SetSystemPowerState(not hibernate, True)
# Restore previous privileges
win32security.AdjustTokenPrivileges(
hToken,
0,
old_privs
)
如果你只想用一行代码,并且已经有了正确的权限(适合一个简单的个人脚本):
import win32api
win32api.SetSystemPowerState(True, True) # <- if you want to Suspend
win32api.SetSystemPowerState(False, True) # <- if you want to Hibernate
注意:如果你的系统禁用了休眠功能,它会进入挂起状态。在第一个函数中,我加了一个检查,至少可以提醒你这一点。