Posts: 13
Joined: Tue Nov 04, 2014 6:59 pm

Rebooting raspbian via Python

Wed Jan 21, 2015 9:04 am

Hello everyone,
I am desperately trying to find out a way to force my Raspberry Pi running Raspbian to restart when a certain condition is met (Python script), however I got no success so far...

I have tried the following statements by using popen:

Code: Select all

sudo reboot -i -p
sudo reboot -f
sudo shutdown -r -f now

Code: Select all

from subprocess import Popen, PIPE

def reboot():
    reboot_statement = "sudo shutdown -r -f now"
    popen_args = reboot_statement.split(" ")
    Popen(popen_args, stdout=PIPE, stderr=PIPE)
I thought the problem could be calling it through the Python application itself, therefore I wrote a small C program to kill all running Python application and then reboot, but no success...

My Raspberry is enough powered (Red LED is always on) and all commands I described above work fine when called directly from the command window.

Any help is appreciated!


User avatar
Posts: 42772
Joined: Sun Jun 16, 2013 11:19 pm
Location: A small cave in deepest darkest Basingstoke, UK

Re: Rebooting raspbian via Python

Wed Jan 21, 2015 9:47 am

raspmangobr wrote:
I have tried the following statements by using popen:
Since there's nothing left to do if the shutdown command works there's no point using popen (which is deprecated in favour of subprocess anyway). You don't need to do anything with the output from a successful shutdown command.

So switch to

Code: Select all

import os
os.system('sudo shutdown -r now')
Languages using left-hand whitespace for syntax are ridiculous

DMs sent on https://twitter.com/DougieLawson or LinkedIn will be answered next month.
Fake doctors - are all on my foes list.

The use of crystal balls and mind reading is prohibited.


Re: Rebooting raspbian via Python

Sun Feb 17, 2019 7:32 pm

Thanks for that DougieLawson - just borrowed this old code snippet.

Search is such a wonderful coding tool :D :lol: :D

Posts: 1
Joined: Wed Feb 26, 2020 11:11 am

Re: Rebooting raspbian via Python

Wed Feb 26, 2020 11:13 am

Just type the following two lines of code:

import os
os.system('sudo reboot')

And your pi would reboot

Return to “Troubleshooting”