【发布时间】:2015-12-27 21:17:51
【问题描述】:
我有一个连接到覆盆子的传感器类型 DHT22。 我在 python 中编写了一个脚本,但是当我运行它时出现错误
#!/usr/bin/python
import MySQLdb
import subprocess
import re
import sys
import time
import datetime
import Adafruit_DHT
conn = MySQLdb.connect("localhost","zeus","gee3g673r","logi")
while(True):
date = time.strftime("%d/%m/%Y")
clock = time.strftime("%H:%M")
#output = subprocess.check_output(["/usr/bin/AdafruitDHT.py 2302", "4"]);
output = Adafruit_DHT.read_retry(Adafruit_DHT.AM2302, 4)
matches = re.search("Temp =\s+([0-9.]+)", output)
if (not matches):
time.sleep(0)
continue
temp = float(matches.group(1))
matches = re.search("Hum =\s+([0-9.]+)", output)
if (not matches):
time.sleep(0)
continue
humidity = float(matches.group(1))
# MYSQL DATA Processing
c = conn.cursor()
c.execute("INSERT INTO data_th (date, clock, temp, hum) VALUES (%s, %s,%s, %s)",(date, clock, temp, humidity))
#print "DB Loaded"
time.sleep(360)
这是运行脚本时遇到的错误:
root@raspberrypi:/home# ./hdt.py
Traceback (most recent call last):
File "./dht.py", line 22, in <module>
matches = re.search("Temp =\s+([0-9.]+)", output)
File "/usr/lib/python2.7/re.py", line 142, in search
return _compile(pattern, flags).search(string)
TypeError: expected string or buffer
【问题讨论】:
-
我唯一注意到的是你在一个字符串中做你的正则表达式。我通常使用这样的原始字符串方法:
searchObj = re.search( r'(.*) are (.*?) .*', line, re.M|re.I) -
您的
output可能不是正确的类型。你能强迫它串起来吗?repr(output)?
标签: python raspberry-pi sensors