How to shutdown a window using python? one-liner Python code

khatrivinay

Vinay Khatri

Posted on July 25, 2022

How to shutdown a window using python? one-liner Python code

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
Enter fullscreen mode Exit fullscreen mode
Shutdown program
import os
os.system("shutdown /s")
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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")
Enter fullscreen mode Exit fullscreen mode

Restart the window using Python

To restart the window immediately, we can raise the /r flag witht the shutdown command.

Command
shutdown /r
Enter fullscreen mode Exit fullscreen mode
Restart program
import os

os.system("shutdown /r ")
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
Restart Program
import os

os.system("shutdown /r /t 10")

print("Your Pc will restart in 10 seconds")
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
Example
import os

comment ="Time for work out"

os.system(f"shutdown /s /t 10 /c {comment}")
Enter fullscreen mode Exit fullscreen mode
💖 đŸ’Ē 🙅 🚩
khatrivinay
Vinay Khatri

Posted on July 25, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related