Sleep / Suspend / Hibernate Windows PC
Asked Answered
N

6

6

I'd like to write a short python script that puts my computer to sleep. I'Ve already searched the API but the only result on suspend has to do with delayed execution. What function does the trick ?

Ness answered 22/9, 2011 at 15:37 Comment(1)
Does PC imply this is on Windows?Couture
B
6

Without resorting to shell execution, if you have pywin32 and 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
    )

If you want just a one-liner with pywin32 and has the right permissions already (for a simple, personal script):

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

Note: if your system has disabled hibernation, it will suspend. In the first function I included a check to at least warn of this.

Brownell answered 7/9, 2016 at 2:30 Comment(0)
C
13

I don't know how to sleep. But I know how to Hibernate (on Windows). Perhaps that is enough? shutdown.exe is your friend! Run it from the command prompt.

To see its options do shutdown.exe /?

I believe a hibernate call would be: shutdown.exe /h

So, putting it all together in python:

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

But as other have mentioned, it is bad to use os.system. Use the popen instead. But, if you're lazy like me and its a little script them meh! os.system it is for me.

Canadian answered 23/11, 2012 at 12:43 Comment(0)
B
6

Without resorting to shell execution, if you have pywin32 and 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
    )

If you want just a one-liner with pywin32 and has the right permissions already (for a simple, personal script):

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

Note: if your system has disabled hibernation, it will suspend. In the first function I included a check to at least warn of this.

Brownell answered 7/9, 2016 at 2:30 Comment(0)
B
2

Get pywin32, it also contains win32security if I remember correctly. Then try the mentioned script again.

Benjamin answered 22/9, 2011 at 22:5 Comment(0)
B
2
import os
os.system(r'rundll32.exe powrprof.dll,SetSuspendState Hibernate')
Basie answered 28/10, 2011 at 1:8 Comment(0)
A
1

If you're using Windows, see this gmane.comp.python.windows newsgroup post by Tim Golden.

Amyamyas answered 22/9, 2011 at 15:44 Comment(1)
I followed your link but the script doesn't work for me. How can I get win32api and win32security, both imports won't work.Ness
G
0
subprocess.call(['osascript', '-e','tell app "System Events" to sleep'])
Godevil answered 8/1, 2020 at 9:38 Comment(1)
While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.Haplite

© 2022 - 2024 — McMap. All rights reserved.