Emery King
Emery King

Reputation: 3534

Does Python timeout after a certain period of time?

I have a Python2 script running in Arch Linux that is designed to loop forever - however, it stops running after so many hours.

Here is the script:

import RPi.GPIO as GPIO
import time
import urllib2
import xml.dom
from urllib2 import Request, urlopen, URLError, HTTPError
from xml.dom import minidom

GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(15, GPIO.OUT)
GPIO.setup(16, GPIO.OUT)
GPIO.output(15, True)
GPIO.output(16, True)

saved_store_pickup_order = False;

while True:
    req = Request('http://www.example.com/apiv2/pi/alerts/')
    try:
        response = urlopen(req)
    except HTTPError as e:
        print 'The server couldn\'t fulfill the request: ', e.code
    except URLError as e:
        print 'Failed to reach server: ', e.reason
    else:
        xml = response.read()
        xmldoc = minidom.parseString(xml)
        store_pickup = xmldoc.getElementsByTagName('current_store_pickup')
        if len(store_pickup):
            current_store_pickup_order = store_pickup[0].childNodes[0].nodeValue

            if not saved_store_pickup_order:
                saved_store_pickup_order = current_store_pickup_order

            if  current_store_pickup_order != saved_store_pickup_order:
                GPIO.output(15, False)
                GPIO.output(16, False)
                saved_store_pickup_order = current_store_pickup_order

    time.sleep(5)
    GPIO.output(16, True)
    time.sleep(25)

I'm wondering if there is a timeout period by default with executing Python scripts.

Also, this script is started at boot by systemd if that makes a difference.

Upvotes: 0

Views: 113

Answers (1)

johntellsall
johntellsall

Reputation: 15180

  1. put the entire loop in a try: except: block

  2. consider moving from print statements to using the logging library.

Example (untested):

import logging
mylog = logging.getLogger(__name__)
mylog.info('start')
while True:
    try:
       out = dostuff(data)
       mylog.debug('got {}, output={}'.format(data, out))
    except KeyboardInterrupt:
       break
    except Exception:
       mylog.exception('uhoh')
mylog.info('done')

Upvotes: 1

Related Questions