Raspberry Pi – Restart / Shutdown your Pi from Python code

Here’s something that you probably won’t want to do, but how can you restart or shut-down your Pi from software in python code?

 

Well it’s both quite simple and quite tricky all at the same time, but in summary you can run some python code like this to shell out to the shutdown command:

 
def restart():
    command = "/usr/bin/sudo /sbin/shutdown -r now"
    import subprocess
    process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
    output = process.communicate()[0]
    print output
 

Executing this python code is like running the following in bash:

 
sudo shutdown -r now
 

Which will reboot the system. Note that the shutdown command is sudo’d and that the full paths to sudo and shutdown are specified.

 

Now for this code to work it must be run in the context of a user that has sufficient privileges (e.g. the pi user). If the python code is being executed by a user that does not have the necessary permissions then the it will not work – for example when running this code as part of my Web2py application the code initially had no effect as it was being run as the apache www-data user.

 

To fix this problem you need to add the user in question (in my case www-data) to the sudoers file (for the shutdown command). Edit the sudoers file by issuing the following command in bash:

 
sudo visudo
 

Then add the following lines to the end of the file remembering to ‘www-data’ to your target user:

 
 
www-data ALL=/sbin/shutdown
www-data ALL=NOPASSWD: /sbin/shutdown
 
 

And hopefully that should do it!

 
2 replies

Comments are closed.