我試圖多執行緒的代碼為“暫停/休眠PC與蟒蛇”提供羅南派尚時,我發現,time.sleep()不暫停的執行緒運行的pywin32模塊。
>>> 警告!以下代碼將使 Windows 進入睡眠狀態 <<<
def suspend(buffer, hibernate=False):
'''Puts Windows to Suspend/Sleep/Standby or Hibernate.
Parameters
----------
buffer: string, for time.sleep()
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()
'''
print('before sleep')
sleep(float(buffer))
print('after sleep')
# 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:
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 __name__ == '__main__':
Thread(target=suspend, args=("10")).start()
該print函式確實等待了time.sleep(),但 Windows 立即進入睡眠狀態。發生了什么?
uj5u.com熱心網友回復:
您在呼叫中Thread錯誤地傳遞了緩沖區引數,因此它只傳遞了sleep1.0 秒。您需要,在args關鍵字引數的值末尾添加一個逗號,如下所示:
.
.
if __name__ == '__main__':
Thread(target=suspend, args=("10",)).start()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/318750.html
標籤:Python 多线程 python-多线程 睡觉 pywin32
上一篇:java.net.SocketException:使用Jmeter并發執行緒組時,套接字在腳本持續時間結束時關閉
