I was trying to multithread the code for “Suspend / Hibernate pc with python” provided by Ronan Paixão when I find that time.sleep()
does not suspend the thread that run pywin32
module.
>>> Warning! The following code will put Windows to sleep <<<
JavaScript
x
60
60
1
def suspend(buffer, hibernate=False):
2
'''Puts Windows to Suspend/Sleep/Standby or Hibernate.
3
4
Parameters
5
----------
6
buffer: string, for time.sleep()
7
hibernate: bool, default False
8
If False (default), system will enter Suspend/Sleep/Standby state.
9
If True, system will Hibernate, but only if Hibernate is enabled in the
10
system settings. If it's not, system will Sleep.
11
12
Example:
13
--------
14
>>> suspend()
15
'''
16
print('before sleep')
17
sleep(float(buffer))
18
print('after sleep')
19
# Enable the SeShutdown privilege (which must be present in your
20
# token in the first place)
21
priv_flags = (win32security.TOKEN_ADJUST_PRIVILEGES |
22
win32security.TOKEN_QUERY)
23
hToken = win32security.OpenProcessToken(
24
win32api.GetCurrentProcess(),
25
priv_flags
26
)
27
priv_id = win32security.LookupPrivilegeValue(
28
None,
29
win32security.SE_SHUTDOWN_NAME
30
)
31
old_privs = win32security.AdjustTokenPrivileges(
32
hToken,
33
0,
34
[(priv_id, win32security.SE_PRIVILEGE_ENABLED)]
35
)
36
37
if (win32api.GetPwrCapabilities()['HiberFilePresent'] == False and
38
hibernate == True):
39
import warnings
40
warnings.warn("Hibernate isn't available. Suspending.")
41
try:
42
windll.powrprof.SetSuspendState(not hibernate, True, False)
43
except:
44
# True=> Standby; False=> Hibernate
45
# https://msdn.microsoft.com/pt-br/library/windows/desktop/aa373206(v=vs.85).aspx
46
# says the second parameter has no effect.
47
# ctypes.windll.kernel32.SetSystemPowerState(not hibernate, True)
48
win32api.SetSystemPowerState(not hibernate, True)
49
50
# Restore previous privileges
51
win32security.AdjustTokenPrivileges(
52
hToken,
53
0,
54
old_privs
55
)
56
57
58
if __name__ == '__main__':
59
Thread(target=suspend, args=("10")).start()
60
The print
function did waited for time.sleep()
, but the Windows was immediately put to sleep.
What happened?
Advertisement
Answer
You’re passing the buffer argument in the call to Thread
incorrectly, so it’s only sleep
ing for 1.0 second. You need to add a comma ,
at the end of value for the args
keyword argument like this:
JavaScript
1
6
1
.
2
.
3
if __name__ == '__main__':
4
Thread(target=suspend, args=("10",)).start()
5
6