codescracker


python

Python Program to Shutdown and Restart Computer



« Previous Program Python Tutorial »


Shutdown and Restart Computer in Python

To shutdown and restart your computer or pc or laptop using python code, you have to first import os library and then use os.system() function with the code "shutdown /s /t 1" and "shutdown /r /t 1" to shutdown and restart your computer in a second. Let's first start with how to shutdown your computer in python.

Caution - Make sure to close all the program before running any of the below program as these program immediately shutdown or restart your computer.

Python Programming Code to Shutdown Computer

Following python program shutdown your computer in a second. As soon as you run the below program on your computer, your computer immediately shutdown in a second.

# Python Program - Shutdown Computer
		
import os
while True:
	check = input("Want to shutdown your computer ? (y/n): ")
	if check == 'n':
		break
	else:
		os.system("shutdown /s /t 1")

Here is the snapshot of the above python code on python idle. When you press ENTER after typing the above code, you shutdown your computer:

python shutdown computer

Python Programming Code to Restart Computer

Following python program restart your computer in a second. To restart your computer in python, just place "shutdown /r /t 1" inside the function, os.system() of os library as shown in the program given below:

# Python Program - Restart Computer
		
import os
while True:
	check = input("Want to restart your computer ? (y/n): ")
	if check == 'n':
		break
	else:
		os.system("shutdown /r /t 1")

Here is the snapshot of the above program written on python idle. To restart your computer just type the above code and press ENTER:

python restart computer

Python Programming Code to Shutdown and Restart Computer

Here is the combine version of the above shutdown and restart program in python. Following python program ask from user to enter the choice to perform the desired action. Choices are given to check either user wants to just shutdown his/her computer or wants to restart his/her computer as shown in the program given here:

# Python Program - Shutdown and Restart Computer
		
import os
while True:
	print("1. Shutdown Computer")
	print("2. Restart Computer")
	print("3. Exit")
	choice = int(input("Enter your choice: "))
	if(choice>=1 and choice<=2):
		if choice == 1:
			os.system("shutdown /s /t 1")
		else:
			os.system("shutdown /r /t 1")
	else:
		break

Here is the snapshot of the above python program written on the python idle:

python shutdown and restart computer

Same Program in Other Languages

You may also like to learn or practice the same program in other popular programming languages:


« Previous Program Python Tutorial »




Tools
Calculator

Quick Links
Signup - Login - Give Online Test