gpt4 book ai didi

python - 为什么我收到 AttributeError : 'NoneType' object has no attribute 'group' ?

转载 作者:太空宇宙 更新时间:2023-11-04 05:54:20 25 4
gpt4 key购买 nike

我创建了一个 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)

线上

最佳答案

如果 re.search 无法在字符串中匹配您的正则表达式,它将返回 None ( documents )。 None 对象根本没有任何属性,因此尝试访问 group 属性会引发错误。

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

例如,你可以这样写:

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

关于python - 为什么我收到 AttributeError : 'NoneType' object has no attribute 'group' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28646039/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com