'shutting down computer (linux) using python
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?
Solution 1:[1]
import os
os.system("shutdown now -h")
execute your script with root privileges.
Solution 2:[2]
The best way to shutdown a system is to use the following codes
import os
os.system('systemctl poweroff')
Solution 3:[3]
any way to shut down...without elevated privileges?
No, there isn't (fortunately!).
Keep in mind that you can use several system features to make privilege escalation for normal users easier:
Solution 4:[4]
Just to add to @BorrajaX 's answer for those using logind (newer fedora systems):
import dbus
sys_bus = dbus.SystemBus()
lg = sys_bus.get_object('org.freedesktop.login1','/org/freedesktop/login1')
pwr_mgmt = dbus.Interface(lg,'org.freedesktop.login1.Manager')
shutdown_method = pwr_mgmt.get_dbus_method("PowerOff")
shutdown_method(True)
Solution 5:[5]
import os
os.system("shutdown now -h")
Execution: sudo python_script.py
In case you need to execute it without root privileges:
import subprocess
import shlex
cmd = shlex.split("sudo shutdown -h now")
subprocess.call(cmd)
Execution: $ python_script.py # no sudo required
Solution 6:[6]
linux:
import subprocess
cmdCommand = "shutdown -h now"
process = subprocess.Popen(cmdCommand.split(), stdout=subprocess.PIPE)
Windows:
import subprocess
cmdCommand = "shutdown -s"
process = subprocess.Popen(cmdCommand.split(), stdout=subprocess.PIPE)
Solution 7:[7]
try this
import os
os.system("sudo shutdown now -h")
this worked for me
Solution 8:[8]
I'am using Fedora and it works with me. all what i need to do is Writing this line in terminal :
$ sudo python yourScript.py
Solution 9:[9]
There is a way to shut down the computer without using elevated permissions.
import os
subprocess.call(['osascript', '-e', 'tell app "system events" to shut down'])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Rahul R Dhobi |
| Solution 2 | |
| Solution 3 | Brian Cain |
| Solution 4 | Roeften |
| Solution 5 | |
| Solution 6 | Ali Nemati |
| Solution 7 | Hamid |
| Solution 8 | Black Kinght |
| Solution 9 | Sachith Muhandiram |
