2011-09-22 102 views
2

我想寫一個簡短的python腳本讓我的電腦進入睡眠狀態。我已經搜索了API,但暫停的唯一結果與延遲執行有關。這個技巧有什麼功能?使用python掛起/休眠pc

+0

PC意味着這是在Windows上嗎? – arunkumar

回答

0

您可以從python腳本運行shell命令。請參閱subprocess module,然後爲您的操作系統搜索適當的命令。

2

獲取pywin32,還含有win32security如果我沒有記錯。然後再次嘗試提到的script

1
import os 
os.system(r'rundll32.exe powrprof.dll,SetSuspendState Hibernate') 
4

我不知道該如何睡覺。但我知道如何休眠(在Windows上)。也許這就夠了? shutdown.exe 是你的朋友!從命令提示符運行它。

以查看其選項做 shutdown.exe /?

相信休眠電話是: shutdown.exe /h

所以,把他們放在一起在python:

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

但在其他已經提到,這是使用os.system。改用popen。但是,如果你像我一樣懶惰,而且有點腳本,他們就是我! os.system它適合我。

2

沒有求助於shell執行,如果你有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 
    ) 

如果你只想要一個班輪與pywin32並已擁有正確的權限(爲簡單,個人腳本) :

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

注:如果你的系統禁用休眠狀態,將暫停。在第一個函數中,我至少包含了一個支票,以提醒您。