使用python暂停/休眠pc

2024-06-09 14:56:30 发布

您现在位置:Python中文网/ 问答频道 /正文

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


Tags: 功能脚本api状态电脑suspend诀窍
3条回答

如果您有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的一行程序并且已经拥有了正确的权限(对于simple,个人脚本):

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

注意:如果您的系统已禁用休眠,它将挂起。在第一个函数中,我包含了一个检查,至少警告了这一点。

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

看看它的选择 shutdown.exe /?

我相信休眠呼叫是: shutdown.exe /h

所以,用python将它们组合在一起:

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

但正如其他人提到的,使用os.system是不好的。改用波本。但是,如果你像我一样懒,还有一个小小的剧本,那就是喵喵!操作系统是给我的。

可以从python脚本运行shell命令。请参阅subprocess module,然后搜索适合您的操作系统的命令。

相关问题 更多 >