In this example, you will learn different methods to Shutdown/Restart Computer.
Note : Before starting to run this examples please make sure to save and close all documents you can lose unsaved document while executing this programs.
To perform operating system level operation like, shutdown and restart we need to import os library. Then we use it.
Example 1: Shutdown Computer
#python program to shutdown computer
import os
choice = input("Shutdown computer? ( yes or no ) : ")
if choice == "yes" or choice == "Yes" or choice == "YES":
os.system("shutdown /s /t 0")
else
exit()
Explanation :
While running, this program will ask user input and if user input yes then it will immediately shutdown system.
Example 2: Restart Computer
#python program to restart computer
import os
choice = input("Do you want to restart computer? ( yes or no ) : ")
if choice == "yes" or choice == "Yes" or choice == "YES":
os.system("shutdown /r /t 0")
else
exit()
Explanation :
This program will ask user to input and restart computer immediately if user input is yes.
Example 3: Log-off User
#python program to log off current user
import os
choice = input("Do you want to log-off current user? ( yes or no ) : ")
if choice == "yes" or choice == "Yes" or choice == "YES":
os.system("shutdown /l")
else
exit()
Explanation :
Here, we are passing /l as argument with shutdown command which means, we are passing commanding system to log off current user.
Above all example will work with windows but if you want to shutdown Linux based system that you can follow this example.
Example 4: Shutdown Linux based system
#python program to shutdown linux based os
import os
choice = input("Do you want to log-off current user? ( yes or no ) : ")
if choice == "yes" or choice == "Yes" or choice == "YES":
os.system("sudo shutdown now")
else
exit()
Explanation :
This program will shutdown any Linux based system immediately.
Ask anything about this examples