为什么我得到一个AttributeError:'NoneType'对象没有属性'group'?

时间:2015-02-21 12:55:26

标签: python arduino

我创造了一个测量花园温度的bareduino。 当我直接从终端从接收器读取串行数据时,我得到了这个:

  

〜$ screen / dev / ttyUSB1 9600

   Requesting temperature...DONE
   Device 1 (index 0) = 19.62 Degrees C
   VCC = 5.89 Volts
   VCC = 96.99 %

   Requesting temperature...DONE
   Device 1 (index 0) = 19.62 Degrees C
   VCC = 5.89 Volts
   VCC = 96.99 %

等等。

我有以下脚本正常工作,但有时经过一段时间的运行我得到一个错误,我不明白。

  

/ var / python $ cat rx4.py

#!/usr/bin/env python
#
# rx4.py serial_port port_speed
#
import serial, sys
import re
import time
import datetime
import pymysql

if (len(sys.argv) != 3):
   print "command line: rx.py serial_port port_speed"
   sys.exit()
port = sys.argv[1]
speed = int(sys.argv[2])
ser = serial.Serial(port,speed)
ser.setDTR()
ser.flushInput()
print 'Welcome to remote bareduino temprature! Waiting for data...'
data = []
while 1:
  count = 0
  data = []
  while (count < 5):
    count += 1
    x = ser.readline()
    data.append(x)
  if data:
    temperatur = re.search(' = (.*?) Degrees C', data[2]).group(1)
    volts = re.search('VCC = (.*?) ', data[3]).group(1)
    batt =  re.search('VCC = (.*?) \%', data[4]).group(1)
  print 'print data'
  print data

  conn = pymysql.connect(host='10.0.0.175', port=3306, user='python', passwd='testcode', db='test2')
  cur = conn.cursor()
  cur.execute("INSERT INTO 28b65eb2(celsius,voltproc,volt) VALUES (%s,%s,%s)", (temperatur, batt, volts))
  conn.commit()
  cur.close
  conn.close()

  print temperatur, u'\u00b0'
  print volts, u'\u26A1'
  print u"\U0001F50B", batt, u"\u0025"
  

/ var / python $ python rx4.py / dev / ttyUSB1 9600

Welcome to remote bareduino temprature! Waiting for data...
print data
['\r\n', 'Requesting temperature...DONE\r\n', 'Device 1 (index 0) = 20.69 Degrees C\r\n', 'VCC = 5.89 Volts\r\n', 'VCC = 96.14 %\r\n']
20.69 °
5.89 ⚡
 96.14 %
print data
['\r\n', 'Requesting temperature...DONE\r\n', 'Device 1 (index 0) = 20.69 Degrees C\r\n', 'VCC = 5.89 Volts\r\n', 'VCC = 96.14 %\r\n']
20.69 °
5.89 ⚡
 96.14 %

我收到此错误:

AttributeError: 'NoneType' object has no attribute 'group'?

temperatur = re.search(' = (.*?) Degrees C', data[2]).group(1)

的行上

1 个答案:

答案 0 :(得分:1)

如果re.search与字符串中的正则表达式不匹配,则会返回Nonedocuments)。 None对象根本没有属性,因此尝试访问group属性会引发错误。

要修复错误,您需要更改正则表达式,以便re.search匹配某些内容,明确检查re.search是否未返回None,如果是,请跳过您访问的行匹配组,或通过try / except阻止来捕获错误。

例如,你可以写:

match = re.search(' = (.*?) Degrees C', data[2])
if match is not None:
     temperatur = match.group(1)
else:
     temperatur = "unknown" # or any other value