2017-01-18 98 views
1

我試着寫是從Mosquitto經紀人訂閱數據,以獲得來自傳感器是在一個特定的主題發佈數據的所有消息和數據發送到MySQLdb的Python腳本MQTT爲了保存數據Python的MySQL的NameError:全局名稱「save_to_db」沒有定義

代碼:

import paho.mqtt.client as mqtt 
import MySQLdb 

def on_connect(client, userdata, flags, rc): 
    print("Connected with result code "+str(rc)) 
    client.subscribe("#") 

def on_message(client, userdata, msg): 
    print(msg.topic+" "+str(msg.payload)) 
     save_to_db(msg) 
client = mqtt.Client() 
client.on_connect = on_connect 
client.on_message = on_message 
client.connect("192.168.0.132", 1883, 60) 

client.loop_forever() 

testdb = MySQLdb.connect("localhost","root","","testdb") 

def save_to_db(msg): 
    with testdb: 
     cursor = testdb.cursor() 
     try: 
      cursor.execute("INSERT INTO pulses (pulse) VALUES (%s)", (msg.payload)) 
     except (MySQLdb.Error, MySQLdb.Warning) as e: 
      print('excepttion BD ' + e) 
      return None 

但錯誤會顯示:

Traceback (most recent call last): 
    File "sub3.py", line 16, in <module> 
    client.loop_forever() 
    File "/usr/local/lib/python2.7/dist-packages/paho/mqtt/client.py", line 1378, in loop_forever 
    rc = self.loop(timeout, max_packets) 
    File "/usr/local/lib/python2.7/dist-packages/paho/mqtt/client.py", line 897, in loop 
    rc = self.loop_read(max_packets) 
    File "/usr/local/lib/python2.7/dist-packages/paho/mqtt/client.py", line 1177, in loop_read 
    rc = self._packet_read() 
    File "/usr/local/lib/python2.7/dist-packages/paho/mqtt/client.py", line 1766, in _packet_read 
    rc = self._packet_handle() 
    File "/usr/local/lib/python2.7/dist-packages/paho/mqtt/client.py", line 2239, in _packet_handle 
    return self._handle_publish() 
    File "/usr/local/lib/python2.7/dist-packages/paho/mqtt/client.py", line 2414, in _handle_publish 
    self._handle_on_message(message) 
    File "/usr/local/lib/python2.7/dist-packages/paho/mqtt/client.py", line 2574, in _handle_on_message 
    self.on_message(self, self._userdata, message) 
    File "sub3.py", line 10, in on_message 
    save_to_db(msg) 
NameError: global name 'save_to_db' is not defined 

回答

2

你開始循環太早:

client.loop_forever() 

任何代碼定義後此線尚未執行,因此,任何功能對象還沒有定義。

將該行下移到以下循環運行時需要存在的任何函數。

+0

感謝,但仍然沒有工作 –

+0

'文件 「sub3.py」,第29行,在 client.loop_forever()' –

+0

@IstabraqMahmood:沒有異常* *的變化,或者是它仍然以其它方式完全一樣?在'client.loop_forever()'行產生輸出之前是否打印(save_to_db)? –

相關問題