How to restart python script automatically?

Hi,
I'm running a infinitly looping python-script at the startup of the linino (with rc.local).
The script is depending on a internet connection, because it sends temperature data from
the yun to a plotting service (plot.ly).

My problem:
Everything works fine...UNTIL the Yun looses its internet connection (can sometimes happen
in my place)... Then the infinitly looping python-script stops to work (guess it throws an exception,
but I don't know how to catch/see that). Tried a while-do-done but could't make it work...

How can I restart the script automatically?

Here is the content of my /etc/rc.local file:

sleep 60
wifi-live-or-reset
sleep 10
ntpd -qn -p 0.openwrt.pool.ntp.org
sleep 10
python /mnt/sd/Script.py

exit 0

Try daemontools ? ( untest method )

http://forum.arduino.cc/index.php?topic=215411.msg1576200#msg1576200

Hi,
thanks for the reply. I couldn't make daemontool work, but I found a way to recall the script itself when there is no internet connection (with pinging google.com)... BUT restarting the script doesn't help if the internet connection won't be established by the yun (even after the internet is up again in my place, the yun sometimes won't reconnect)... so I think restarting the yun itself or the wifi with a script is the best solution when loosing internet connection.

But how can we restart it with a script?!

in /etc/rc.local there is the line "wifi-live-or-reset", which works at boot...but how to run it LATER (e.g. when my skript will recognize internet outage) ?! Or is there a better solution to restart the yun (or wifi) ?!

Please no constant ping google.com , you (your ip address) might get banned.

Yun losts connecting to Internet from time to time.

http://forum.arduino.cc/index.php?topic=203754.msg1507343#msg1507343

Yun internet-live-led

http://forum.arduino.cc/index.php?topic=209412.msg1541242#msg1541242

#!/bin/sh
HOSTS="8.8.8.8"  #google's dns server
ping_attempts=1
sleep_time=5
while true
do
	count=$(ping -c $ping_attempts $HOSTS | awk -F, '/received/{print $2*1}')
	#echo $count
	if [ $count -eq 0 ]; then
	# no internet do clean job, kill bridge  and your script
	else
	# check if your script is running , if not start your script
	fi
	sleep  $sleep_time
done

This was a great tip, thanks! I implemented your code (but with blinking wifi led), so I can see if the internet is up or not.

But my script is designed to infinitly loop, therefore I can't just insert the script in your code (without changing it alot).

It would be a lot better, if there was a way to restart the yun completly when Internet drops...

Hope you understand my problem!

Take a look at these:

my /etc/rc.local:

sleep 50
wifi-live-or-reset

sleep 2
/usr/bin/internet-live-led &   # YOUR Script

sleep 2
ntpd -qn -p 0.openwrt.pool.ntp.org     # get the time

sleep 9
python /mnt/sd/TempPlotly.py # MY INFINITLY LOOPING Script

exit 0

So I guess I just somehow need to add a line of "restart yun"-code in your script:

#!/bin/sh

HOSTS="8.8.8.8"
ping_attempts=1
sleep_time=10

while true
do
        count=$(ping -c $ping_attempts $HOSTS | awk -F, '/received/{print $2*1}')
        #echo $count
        if [ $count -eq 0 ]; then      # IF INTERNET DOWN
        /usr/bin/blink-stop 
        
        { "RESTART YUN" - CODE, MAYBE SOMEHOW START wifi-live-or-reset }
       
        else                    # IF INTERNET UP
        /usr/bin/blink-start 100
        fi
        sleep  $sleep_time
done

I am unsure reboot Yun is going to solve your problem. You said Yun looses its internet connection, I guess same time other computer in same network looses internet connection as well? If not then first thing is fix Yun network setting. You infinitly looping python-script should have error handling, internet detection ( merge internet-live-led sh script into python), auto restart.

Fix Internet problem, Connect WiFi A, B and C ( ISP A, ISP B and ISP C)...same time.

http://forum.arduino.cc/index.php?topic=223696.msg1621167#msg1621167

Thanks again, for your input. I already implemented some sort of
#INTERNET-ERROR-HANDLING (tagged the relevant code-parts this way in my script below)
into my script, BUT somehow the Skript won't reconnect to the internet, once the internet is up again...

I wrote many comments for you into my script, so you can have a fast look over it

My infinitly looping script (please don't forget, that I start this script with rc.local):

import time
import sys
import os
import datetime
import plotly
from array import *

# BASICALLY THIS PYTHON SCRIPT (SHALL) INFINITLY 
#       1. OPENS THEN READS A LINE OF A datalog.txt-FILE INTO A ARRAY (content: Arduino-Sketch 
#             generates (and fills) datalog.txt-file constantly every 5-6 sec and writes comma-seperated temperatures 
#             of sensors into a line of the datalog.txt ) 
#       2. THEN TRANSFERS THE TEMPERATURES TO A PLOTTING SERVICE (needs to be almost LIVE/max. 20 sec delay)
#       3. THEN DELETES THE datalog.txt AND WAITS FOR MY ARDUINO-SKETCH TO RECREATE THE datalog.txt
#
# AND IF THE INTERNETS SOMEHOW DOWN THE SCRIPT (SHALL) "WAITS" UNTIL INTERNET IS UP AGAIN <<<---- PROBLEM

______

( I cut this part, because its not relevant AT ALL (layout of plots, login-data etc.). I'm sure about this)

______

x = datetime.datetime.now()  # DATE AND TIME ARE ESSENTIAL FOR TEMPERATURE-PLOTTING !

print x

responseping = os.system("ping -c 1 google.com") # PING FOR INTERNET-ERROR-HANDLING   

# AS LONG AS THERE IS A LINE IN datalog.txt THIS 'WHILE' SHALL READ, 
# then TRANSFER TEMP-data, then DELETE datalog.txt then WAIT some sec
while line:  
  if (responseping == 0): # INTERNET-ERROR-HANDLING-if
      if (len(line) > 1): # FILE-LINE-NOT-EMPTY
          # nLines = nLines + 1
          words = line.split(' ')
          if (len(words) == 2):
              fields = words[1].split(',')
              timeo = fields[0].strip()
              
              temp1 = fields[1].strip()
              temp2 = fields[2].strip()
	      print temp2
              dewy = fields[3].strip()
              
              time.sleep( 2 )
              x = datetime.datetime.now()  # get date/time again (so that time is always correct during the WHILE)
              
	      data = [{'x': x,     # x-axis is time
                       'y': temp1,  # y-axis is first sensors temperature
                       'name':'Raum 1',
		       'type':'scatter',
		       'marker': {'symbol':'square','color':'blue'}
                      },
                      {'x': x,
                       'y': temp2,
                       'name':'Raum 2',
		       'type':'scatter',
		       'marker':{'color':'purple'}
                      },
                      # Testing a second y-axis at the right side of the plot for humidity levels
		      {'x': x,
		       "y": [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25], 
		       "yaxis":"y2",
		       'name':'Feuchtigkeit Raum 3'
		      }
                     ]
              
              # INTERNET-ERRORHANDLING-AGAIN (if WHILE was already entered the moment that the internet went down):
              responseping3 = os.system("ping -c 1 google.com") 
              if ( responseping3 == 0 ):
                response = py.plot(data, filename='Plot-Name' , fileopt='extend', layout=layout)
                url = response['url']
              
              # THIS (SHALL) RESTARTS THE SCRIPT IF SOMEHOW INTERNETS DOWN (not sure if it works):
              else:          
                python = sys.executable
                os.execl(python, python, * sys.argv)

          line = file.readline() 
          file.close()

          # FILE-DELETION AND OPENING AFTER WAITING SOME SEC
          if (os.path.isfile("/tmp/datalog.txt")):
              os.remove("/tmp/datalog.txt")
              time.sleep( 15 )
              data_filename = "/tmp/datalog.txt";
              file = open(data_filename, 'r')
              line = file.readline()
         
          # datalog.txt-FILE-JET-NOT-AVAILABLE-HANDLING:
          else:                      
              time.sleep( 7 )
              file = open(data_filename, 'r')
              line = file.readline()          
                         
      else: # FILE-LINE-EMPTY
          line = file.readline() 
  
  # INTERNET-ERROR-HANDLING-else

  else:
     if (os.path.isfile(data_filename)):
       file.close()
       time.sleep( 20 )
       if (os.path.isfile("/tmp/datalog.txt")):
         file = open(data_filename, 'r')
         line = file.readline()

         # INTERNET-ERROR-HANDLING

         responseping = os.system("ping -c 1 google.com")
         if (responseping != 0):
           python = sys.executable
           os.execl(python, python, * sys.argv)
           


os.remove("/tmp/datalog.txt")
print "While ende" # SHOWS ME IF WHILE SOMEHOW UNINTENTIONALLY ENDS

# END OF MY SCRIPT

Maybe we could somehow make YOUR script return some value, so that my script knows when internet is up or not?!
If internet is not up, my script should be aborted or killed or waiting...and then your script could restart my script? But how do I accomplish this?!

I forgot to mention, that I tried your other solution etc:

  1. luci-app-multiwan couldn't be found by opkg install... maybe its not available anylonger or its not compatible?
  2. I installed and tested multiwan but couldn't make it work...actually I broke my entiry connection to the yun and needed to reconfigure everything. In the aftermath I think its not really an option for me, because I can't connect the Yun to 2 ISPs (e.g. LAN to one ISP and Wifi to another ISP)
  3. I added the missing line to the dhcp-file (the known dhcp issue of openwrt)

I've done some tests in order to see if the yun automatically reconnect to the network and It does. I configured my Yun to connect to an access point, and if I turn off the AP and then turn on again, the Yun recover the connection. I waited 5 minutes and 2 hours before turning on the AP and I tried with WPA2 and with no encryption. I have the latest version of the firmware on my Yun.