赋值前引用的变量:Python
variable referenced before assignment: Python
我正在尝试从 raspberry pi 3 获取数据到 Azure
该脚本从 Raspberry Pi3 读取数据,Raspberry Pi3 通过蓝牙连接到传感器并获取多个值。
不幸的是我收到一个错误,当我 运行 它
"local variable 'temperature' referenced before assignment"
def iothub_client_sample_run():
msgs=[]
for address, name in list(devices.items()):
try:
client = iothub_client_init()
if client.protocol == IoTHubTransportProvider.MQTT & (name == "Flower care"):
msg_txt_formatted = MSG_TXT % (
temperature,
sunlight,
moisture,
fertility)
message = IoTHubMessage(msg_txt_formatted)
# optional: assign ids
message.temperature_id = "%d" % temperature
client.send_event_async(message, send_confirmation_callback, devices.items())
print ( "IoTHubClient.send_event_async accepted message {} for transmission to IoT Hub.".format(devices.items()) )
return msgs
while 1:
msgs=iothub_client_sample_run()
for msg in msgs:
print msg['topic']
print msg['payload']
(result, mid)=mqttc.publish(msg['topic'],msg['payload'])
print ( "Send status: %s" % status )
time.sleep(10)
mqttc.disconnect()
except IoTHubError as iothub_error:
print ( "Unexpected error %s from IoTHub" % iothub_error )
return
except KeyboardInterrupt:
print ( "IoTHubClient sample stopped" )
print_last_message_time(client)
这里的错误信息很清楚。
请记住,Python 一次读取并执行一行代码,因此如果您在使用它的函数之后声明了一个变量,那么它将抛出一个错误。调整您的代码以在调用变量之前放置变量,您应该不会再遇到此错误。
我正在尝试从 raspberry pi 3 获取数据到 Azure
该脚本从 Raspberry Pi3 读取数据,Raspberry Pi3 通过蓝牙连接到传感器并获取多个值。
不幸的是我收到一个错误,当我 运行 它
"local variable 'temperature' referenced before assignment"
def iothub_client_sample_run():
msgs=[]
for address, name in list(devices.items()):
try:
client = iothub_client_init()
if client.protocol == IoTHubTransportProvider.MQTT & (name == "Flower care"):
msg_txt_formatted = MSG_TXT % (
temperature,
sunlight,
moisture,
fertility)
message = IoTHubMessage(msg_txt_formatted)
# optional: assign ids
message.temperature_id = "%d" % temperature
client.send_event_async(message, send_confirmation_callback, devices.items())
print ( "IoTHubClient.send_event_async accepted message {} for transmission to IoT Hub.".format(devices.items()) )
return msgs
while 1:
msgs=iothub_client_sample_run()
for msg in msgs:
print msg['topic']
print msg['payload']
(result, mid)=mqttc.publish(msg['topic'],msg['payload'])
print ( "Send status: %s" % status )
time.sleep(10)
mqttc.disconnect()
except IoTHubError as iothub_error:
print ( "Unexpected error %s from IoTHub" % iothub_error )
return
except KeyboardInterrupt:
print ( "IoTHubClient sample stopped" )
print_last_message_time(client)
这里的错误信息很清楚。
请记住,Python 一次读取并执行一行代码,因此如果您在使用它的函数之后声明了一个变量,那么它将抛出一个错误。调整您的代码以在调用变量之前放置变量,您应该不会再遇到此错误。