1
Mosquittoブローカーの購読データである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
おかげで、それでも client.loop_foreverで、 –
'ファイル "sub3.py"、ライン29を動作していない()' –
@IstabraqMahmood:例外*変更*を、やったか、そうでなければ、正確には同じですか? 'client.loop_forever()'行の直前で 'print(save_to_db)'が出力を生成しますか? –