anthrx anthrx -4 years ago 114
Python Question

Raspberry Pi - is it possible to restart a python program, if an error occures and interrupts the running code?

I was wondering if it was possible to restart a python program (automatically ofc, preferably with an easy script) it case it encounters a problem and closes it. My algorithm sometimes doesn't function the way I want it to, but it doesn't really matter if I am able to get it to restart.

Code:

dongle = serial.Serial(port='/dev/ttyUSB0',baudrate=9600,timeout=0,rtscts=0,xonxoff=0)
ard = serial.Serial(port="/dev/ttyACM0", baudrate=9600)
time.sleep(0.5)
while True:
# ard.open()
discard = ard.readline()
string = ard.readline()
print discard
print string
time.sleep(0.5)
temperature, truebung, latitude, longtitude = string.split(",")


Basically, what's happening once every 10 times, is that "string" is corrupt. It does not give me the data I want it to. It misses something or gives me a random value. Normally, the string should look something like this "24.04,0.23,18.92442,40.25255" but it sometimes is corrupt and looks like this "40.25255" or ".25255". I "ard.readline" twice because originally, the "discard" was always corrupt, now the string is also corrupt. What can I do to fix that? It doesn't matter if string isn't correct once every 10 times but it crashes my program and that's the thing I want it not to do.

Answer Source

I'm gonna go out on a limb here and assume that your program crashes with ValueError on the last line:

temperature, truebung, latitude, longtitude  = string.split(",")

when there aren't enough elements. The error should be something like ValueError: not enough values to unpack (expected 4, got [x]) If so, the fix is pretty simple. The code below should prevent your program from crashing if I guessed your error code correctly.

try:
    temperature, truebung, latitude, longtitude  = string.split(",")
except ValueError:
    print "corrupt string" # and whatever else you want to do to handle the error
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download