Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a Windows 10 computer go to sleep with a python script?

How can I make a computer sleep with a python script?

It has to be sleep, not hibernate or anything else.

I have tried to use cmd but there is no command to sleep or I didn't find one.

like image 983
Squash Avatar asked May 03 '16 16:05

Squash


People also ask

How do I make python sleep on my computer?

Adding a Python sleep() Call With time.sleep() Python has built-in support for putting your program to sleep. The time module has a function sleep() that you can use to suspend execution of the calling thread for however many seconds you specify.

Do Python scripts run when computer is asleep?

The script stops running, assuming it's running on the computer that sleeps/shuts down/hibernates.

How do I put the sleep command in Windows 10?

Hit the R key to restart. Press S to put Windows to sleep. Use H to hibernate.


2 Answers

You can use

import os
os.system("rundll32.exe powrprof.dll,SetSuspendState 0,1,0")

If this command doesn't work for you (it actually puts your comp. in hibernation mode) you will need to turn hibernation off:

Powercfg -H OFF

To turn hibernation mode back on:

Powercfg -H ON

Alternatively, you can also use:

Rundll32.exe Powrprof.dll,SetSuspendState Sleep

If you don't want to turn hibernation off just to run a command, you can use psshutdown as an alternative

C:\Windows\System32\psshutdown.exe -d -t 0 

As for what os.system does, straight from the documentation:

Execute the command (a string) in a subshell.

An additional note:

You will need to have administrator permissions to run Powercfg -H *

like image 145
Pythonista Avatar answered Nov 01 '22 12:11

Pythonista


rundll32.exe powrprof.dll,SetSuspendState 0,1,0 

should work. Note 0,1,0 - that set is for sleep. Without - hibernation.

like image 44
Alex Belotserkovskiy Avatar answered Nov 01 '22 11:11

Alex Belotserkovskiy