shutting down computer (linux) using python

user3522859 picture user3522859 · Apr 11, 2014 · Viewed 43.2k times · Source

I am trying to write a script that will shut down the computer if a few requirements are filled with the command

    os.system("poweroff")

also tried

    os.system("shutdown now -h")

and a few others. but nothing happens when I run it, the computer goes through the code without crashing or producing any error messages and terminates the script normally, without shutting down the computer.

How does one shutdown the computer in python?

edit:

Seems that the commands I have tried requires root access. Is there any way to shut down the machine from the script without elevated privileges?

Answer

Rahul R Dhobi picture Rahul R Dhobi · Apr 11, 2014
import os
os.system("shutdown now -h")

execute your script with root privileges.