Nishadh KA

Checkng Null in Python for loop

2014-07-15


Checking for null in python

  1. The Dylos montior, connected with tp-link and to upload data to thinkspeak internet of things services, following script is used,

    import sqlite3 as lite
    import logging
    import httplib, urllib
    from time import localtime, strftime
    import time
    
    logger = logging.getLogger('lbm1')
    hdlr = logging.FileHandler('/home/pi/SMS/pyts.log')
    formatter = logging.Formatter('%(asctime)s: %(levelname)s %(message)s')
    headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain"}
    conn = httplib.HTTPConnection("api.thingspeak.com:80")
    
    hdlr.setFormatter(formatter)
    logger.addHandler(hdlr)
    logger.setLevel(logging.INFO)
    logger.info("tss")
    
    con = lite.connect('/home/pi/SMS/dylos.db')
    try:
      with con:
        cur = con.cursor()
        cur.execute("SELECT * FROM data ORDER BY SNo DESC LIMIT 1")
        a= [str(i[1]) for i in cur.fetchall()]
        b = map(str.strip,a)
        c= str(b).strip("[']")
        d= c.split(',')
        if d[1] is None:
           d[1]='00'
        if d[2] is None:
           d[2]='00'
        logger.info("dfdb")
        params = urllib.urlencode({'field1': d[1], 'field2': d[2],'key':'1ACXSOW1ZFCYWGZF'})
        conn.request("POST", "/update", params, headers)
        response = conn.getresponse()
        conn.close()
        logger.info('sdf')
    except:
        logger.exception('dbyr')
    finally:
       if con:
          con.close()
    
  2. The Dylos air quality monitor has a problem in its SERIAL. It is defunct in initial startup up to three hours, which collect data for 0.5 micrometers only and omitting 2.5 micrometers. Makes problem in running the script with error, list index out of range, this can be rectified by simple null checking using if.

  3. Based on this, found a method to handle null exception in list out of range case, the command used was gotdata = a[2] if len(a) > 2 else '000' and ['2014-07-15T09:27', '2221']