5

我想编写一个简短的 python 脚本,让我的计算机进入睡眠状态。我已经搜索了 API,但挂起的唯一结果与延迟执行有关。诀窍是什么功能?

4

6 回答 6

11

我不知道怎么睡觉。但我知道如何休眠(在 Windows 上)。也许这就足够了? shutdown.exe 是你的朋友!从命令提示符运行它。

要查看其选项 shutdown.exe /?

我相信休眠调用将是: shutdown.exe /h

因此,将它们放在 python 中:

import os
os.system("shutdown.exe /h")

但正如其他人所提到的,使用 os.system是不好的。改用popen。但是,如果你像我一样懒惰,那就是一个小脚本,嗯!os.system 它是给我的。

于 2012-11-23T12:43:07.080 回答
5

如果您有 pywin32 和 ctypes,则无需求助于 shell 执行:

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
    )

如果您只想要一个带有 pywin32 并且已经拥有正确权限的单行代码(对于一个简单的个人脚本):

import win32api
win32api.SetSystemPowerState(True, True)  # <- if you want to Suspend
win32api.SetSystemPowerState(False, True)  # <- if you want to Hibernate

注意:如果您的系统禁用了休眠,它将暂停。在第一个函数中,我包含了一个检查以至少对此发出警告。

于 2016-09-07T02:30:25.147 回答
2
import os
os.system(r'rundll32.exe powrprof.dll,SetSuspendState Hibernate')
于 2011-10-28T01:08:18.767 回答
2

获取pywin32win32security ,如果我没记错的话,它也包含。然后再次尝试提到的脚本

于 2011-09-22T22:05:29.710 回答
1

如果您使用的是 Windows,请参阅 Tim Golden 的此gmane.comp.python.windows新闻组帖子

于 2011-09-22T15:44:38.750 回答
0
subprocess.call(['osascript', '-e','tell app "System Events" to sleep'])
于 2020-01-08T09:38:33.157 回答