我正在閱讀從Python中的GSM調制解調器接收的消息中的一些數據。使用Python將從GSM調制解調器讀取的消息參數寫入MySQL
我需要在將這些數據寫入我的MySQL數據庫之前提取這些數據參數。
在我這樣做之前,我已經準備好將它寫入數據庫,然後在幾個階段解析消息。
從GSM調制解調器讀取和寫入是通過使用串行對象電話完成的。該串行對象讀入數據臨時存儲的x,直到下一次讀/寫發生。
這裏的控制程序中的流程:
def reading():
print "Reading all the messages stored on SIM card"
phone.write(b'AT+CMGL="ALL"\r') #Command to read all the messages
sleeps()
x=phone.read(100000000)
sleeps()
print x
print "Now parsing the message!"
k="".join(x)
parse(k)
k=""
def parse(k):
match = re.finditer("\+CMGL: (\d+),""(.+)"",""(.+)"",(.*),""(.+)""\n(.+)\n", k)
for each in match:
break_down(each.group(6))
這裏有正在讀多條消息。 each.group(6)包含實際的消息內容。
def break_down(s):
c=s.count('<')
if c==9:
res = re.findall('< (.*?) >', s)
for index in res:
print index,item
elif c==7 or c==3:
temp=parsing(s)
pprint(list(temp))
else:
flag=0
c=s.count(':')
if c==8:
res=s.split(' : ')
res=[item.strip() for item in s.split(':')]
for index, item in enumerate(res):
print index, item
results = [float(x) for x in s.split(' ') if x.count('.') == 1]
pprint(results)
dbinsert(res[0],res[1],res[2],res[3],results[0],results[1],results[2],results[3],flag)
if c==7:
flag=1
res=s.split(' : ')
res=[item.strip() for item in s.split(':')]
for index, item in enumerate(res):
print index, item
results = [float(x) for x in s.split(' ') if x.count('.') == 1]
pprint(results)
dbinsert(res[0],res[1],res[2],res[3],results[0],results[1],results[2],results[3],flag)
def parsing(s):
for t in s.split('<'):
for u in t.strip().split('>',1):
if u.strip(): yield u.strip()
def dbinsert(a,b,c,d,e,f,g,h,flag):
import MySQLdb
db = MySQLdb.Connect(host="127.0.0.1", port=3306, user="root", passwd="root", db="ups")
print "In dbinsert"
cursor = db.cursor()
try:
if flag==0:
sql = """INSERT INTO data(F1,
F2, F3, F4, F5, F6, F7, F8)
VALUES (a.value,b.value,c.value,d.value,e.value,f.value,g.value,h.value)"""
cursor.execute(sql)
db.commit()
elif flag==1:
sql = """INSERT INTO data(F1,
F2, F3, F4, F5, F6, F7, F8)
VALUES (a,b,c,,e,f,g,h)"""
cursor.execute(sql)
db.commit()
except:
db.rollback()
db.close()
break_down(s)能夠精確地根據需要提取數據。但是,一旦將這些數據傳遞給dbinsert,數據就不會寫入數據庫。當我嘗試在沒有其他代碼的情況下使用某些虛擬值進行隔離時,沒有任何問題。所以這不是數據庫連接問題。
我在做什麼錯?
請幫忙。
你怎麼知道break_down正在獲取正確的數據?如果在插入數據之前打印res和results數組,您會看到數據?您可以嘗試使用打印的相同值,而不是使用虛擬值。 – bbayles
是的,這就是我的意思,當我嘗試。它不工作。 – Anon
當你真正運行它時,你看到「在dbinsert中」嗎? – bbayles