Python会在一段时间后超时吗?

时间:2014-05-28 18:23:56

标签: python archlinux

我有一个在Arch Linux中运行的Python2脚本,它可以永久循环 - 但是,它会在这么多个小时后停止运行。

这是脚本:

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)

我想知道默认情况下执行Python脚本是否存在超时期限。

此外,如果有所不同,此脚本将在systemd启动时启动。

1 个答案:

答案 0 :(得分:1)

  1. 将整个循环放在try: except:

  2. 考虑从print语句转到使用logging库。

  3. 示例(未经测试):

    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')