0

I have a very small and simple python script on my raspberry, it works well for as long as there is an active Wi-Fi connection. The raspberry is connected to a mobile hotspot and it's possible it will lose it's connection as it could get out of range. As soon as this happens it throws an exception and ends the request "while" loop.

I was hoping to get more information to how i can make this script pause or "ignore" the exception so it goes back into the loop as soon as the connection is restored.

    import urllib
    import serial
    from time import sleep

    link = "http://myurl/"
    while True:
        f = urllib.urlopen(link)
        myfile = f.read()
        print myfile
        ser = serial.Serial('/dev/ttyUSB0', 9600)
        ser.write(myfile)
        sleep(3)
Rogier
  • 25
  • 1
  • 3

1 Answers1

0

You can try something called, (obviously) a try statement!

Within your while loop, you can use a try: except block to make sure that even if your code does't execute (your pi loses connection or something else weird happens) you won't end the program!

This type of code would look like this:

import urllib
import serial
from time import sleep

link = "http://myurl/"
while True:
    try:
         f = urllib.urlopen(link)
         myfile = f.read()
         print myfile
         ser = serial.Serial('/dev/ttyUSB0', 9600)
         ser.write(myfile)
         sleep(3)
    except:
         sleep(3) #If the code executed in the try part fails, then your program will simply sleep off 3 seconds before trying again!
cosinepenguin
  • 1,545
  • 1
  • 12
  • 21
  • Thank you so much, i searched for a lot of these exception rules but i never saw the simplicity in which it could be used. This works like a charm! – Rogier Nov 03 '17 at 18:25
  • What is I don't use sleep and under `except:` just use `pass`? Will it retry immediately? – wondim Oct 19 '18 at 09:14
  • This other [SO post](https://stackoverflow.com/q/21553327/7299505) will be useful. – cosinepenguin Oct 19 '18 at 18:44