How to restart, shutdown or log out a computer through Python script

Python is one of the languages with the most versatile features. Today we will explore one of these features in Python. We will write a code in Python that will help to restart, shutdown and even log out a local computer automatically.

Requirements: To perform any of the above tasks through the Python script we need to import the ‘os library’. We can do this by the command, ‘pip install os’.

Note: We should close all the other programs and save them before we run the codes mentioned below. This is because these codes will immediately shut down or restart the computer.

1. Shutdown the computer using Python

Command used: shutdown /s /t 1

Code:

import os
Input = input("Want to shutdown now? (Y/N): ")
if Input == 'N':
    exit()
else:
    os.system("shutdown /s /t 1")

Output:

Want to shutdown now? (Y/N):

We get this output on the computer screen where we get an option to choose between the two choices and we have to input our choice. If we input ‘Y’, the computer shutdowns immediately.

2. Restart the computer in Python

Commands used: shutdown /r /t 1

Code:

import os;
Input = input("Want to restart now? (Y/N): ")
if Input == 'N':
    exit()
else:
    os.system("shutdown /r /t 1")

Output:

Want to restart now? (Y/N):

We get this output on the computer screen where we get an option to choose between the two choices and we have to input our choice. If we input ‘Y’, the computer restarts immediately.

3. Log out of the computer using Python

Commands used: shutdown -l

Code:

import os 
  
Input = input("Want to log out now? (Y/N): ") 
  
if Input == 'N': 
    exit() 
else: 
    os.system("shutdown -l")

Output:

Want to log out now? (Y/N):

We get this output on the computer screen where we get an option to choose between the two choices and we have to input our choice. If we input ‘Y’, the computer will log out immediately.

Also read: Shutdown and Restart PC using Python

Leave a Reply

Your email address will not be published. Required fields are marked *