หน้าเว็บ

วันพฤหัสบดีที่ 8 ตุลาคม พ.ศ. 2563

Raspberry Pi – Restart / Shutdown your Pi from Python code

 ที่มา: https://www.ridgesolutions.ie/index.php/2013/02/22/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!


ไม่มีความคิดเห็น:

แสดงความคิดเห็น