Shutdown & Restart Your Computer Using Python
With the help of python OS module you can easily shutdown & restart your system. Do you want to know how? Then this article is for you.
The OS is a Python’s standard utility module which provide functions for interacting with the operating system. OS module include many functions which helps us to interact with the file system. From handling the current working directory, creating a directory, listing out files & directory, deleting files & directory, reading or writing files, we can do all those things using python OS module. We can even shutdown & restart our system using OS module. With the help of few lines of code wecan do it.
Note: Before shutdown your system be sure to save and close all running files because after executing these codes, your system gets shutdown and you can lost your unsaved documents.
Code Snippet For Shutdown
import os
shutdown = input("Do you want to shutdown your computer ? (yes / no): ")
if shutdown == 'no':
exit()
else:
os.system("shutdown /s /t 1")
Explanation
first import the os library.
import os
Then use os.system() to shutdown the system. As soon as you run the program given below, your computer gets shutdown after default time i.e. 30 seconds.
os.system("shutdown /s")
To shutdown the system immediately, provide the timer as 0 second. Here /t stands for timer and 1 indicates 1 second. Therefore after executing this program, system gets shutdown within 1 second.
os.system("shutdown /s /t 1")
Code Snippet To Restart
To restart your computer system using a python program, just replace the /s with /r from the program given to shutdown the system.
import os
os.system("shutdown /r /t 1")
Above program will restart your system within 1 second.
If you want to shutdown or restart your system immediately just replace 1 with 0. It will start executing immediately and make sure to save & close all the files because you will lost it after executing.
Shutdown/Restart based on User’s Choice
import os
print("1. Shutdown")
print("2. Restart")
print("3. Exit")
print(end="Enter Your Choice: ")
choice = int(input())
if choice==1:
os.system("shutdown /s /t 1")
elif choice==2:
os.system("shutdown /r /t 1")
elif choice==3:
exit()
else:
print("Wrong Choice!")
Output
Your system will shutdown/restart after pressing 1 & 2 respectively.
I hope you liked this article. If you have any question feel free to ask in the comment section below.