Although windows provide a graphical user interface to showdown, restart, logoff, and hibernate our computer. But we can also write a Python script to showdown or restart our window with specified time intervals.
Shutting down the computer is an operating system functionality, so to achieve this in Python, we can use the Python inbuilt os module to interact with the operating system.
Shut Down the Window using Python
Windows provide the shutdown /s terminal command to shut down the wind. And it will immediately shut down the computer.
Command
shutdown /s
Shutdown program
import os
os.system("shutdown /s")
Note: The system() method will execute the shutdown /s command for the window.
Shut Down the Window after a specific period in Python
The shutdown command also accepts the /t flag for the period shutdown. It comes very handy when we want to set the time-out period before shutdown.
Command
shutdown \s \t xxx
Note: xxx are the number of seconds for the shutdown.
Shutdown program
import os
os.system("shutdown /s /t 10")
print("Your Pc will shut down in 10 seconds")
Restart the window using Python
To restart the window immediately, we can raise the /r flag witht the shutdown command.
Command
shutdown /r
Restart program
import os
os.system("shutdown /r ")
Restart the Window after xxx seconds
We can also specify the xxx number of seconds to set a restart process. To set the time period we can use the /t flag and specify the xxx seconds.
Command
shutdown /r /t 10
Restart Program
import os
os.system("shutdown /r /t 10")
print("Your Pc will restart in 10 seconds")
Restart and shut down with a comment
We can also specify the reason, message, or comment for the shutdown or restart processes, so we can know why we initiated the shutdown or restart.
Command
shutdown /s /c message
Example
import os
comment ="Time for work out"
os.system(f"shutdown /s /t 10 /c {comment}")
Top comments (0)