This is how you can shut down your computer using python.

import os

# Shutdown the computer
os.system("shutdown /s /t 1")

If you run the above code, your computer will be turned off in a second. Beautiful, isn’t it? I know. With only two lines of code, you can turn off your computer using python. I’d like to see java do that😝

Now let’s talk about how the code works:

Importing the os module

from line 1, we have this:

import os

So from the above code, what we are doing, is importing the os module. For those who may not be aware, the os module, is a module that is used in python to access operating system functionalities; including the functionality of shutting down a computer.

Now the next line in our code happens to be a comment, and I not going to be explaining that. Everyone knows what a comment does. So by seeing it, I sure you understand it.

Using the os.system function

So the last line in our code, is what is responsible for handling the shutting down of our computer.

This line:

os.system("shutdown /s /t 1")

So what we did here, was to access the system function from the os module we imported earlier, and pass in our arguments based on what we want the computer to do.

What the arguments do

Here’s what the arguments do:

shutdown: This is the command that shuts down the computer

/s: This is a flag that is used to denote the shut down action. /s is stands for shutdown

/t: This is used to set how long the computer will wait before shutting down.

1: This is the value that shows how long the computer will wait for before shutting down.

So in this post, we have learnt how to shut down a computer using python code. And what our code is essentially doing is, making use of the command-line command (shutdown /s /t 1) to shut down the computer.

The command we learnt, is responsible for shutting down a computer in command prompt. There are other command-line commands out there, and they can also be used in python (the same way we have used this one) using the os.system function.