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:

 

 

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

 

 

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:

 

 

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

 

 

And hopefully that should do it!

 
2 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

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