【问题标题】:NameError: name 'msg' is not definedNameError:未定义名称“msg”
【发布时间】:2021-08-27 08:54:58
【问题描述】:
def on_message(client, userdata, message):
    global msg
    #print("message received " ,str(message.payload.decode("utf-8")))
    #print("message topic=",message.topic)
    #print("message qos=",message.qos)
    #print("message retain flag=",message.retain)
    msg = str(message.payload)

broker_address="10.87.7.27"
print("creating new instance")
client = mqtt.Client("P1") #create new instance
client.on_message= on_message #attach function to callback
print("connecting to broker")
client.connect(broker_address,1883) #connect to broker
client.loop_start() #start the loop
print("Subscribing to topic","home/kitchen/output/lights/set")
client.subscribe("Sekurit_KTBlower_Optimizer_write")
time.sleep(10) 

print(msg)
dict_str = msg.decode("UTF-8")
#jsonload = json.loads(dict_str)
mydata = ast.literal_eval(dict_str)
Lowerpredict = mydata["Lowerpredict"]
Upperpredict = mydata["Upperpredict"]

print(Lowerpredict,UpperPredict)
client.loop_stop() #stop the loop

我收到一个错误,因为“NameError: name 'msg' is not defined” 直到 time.sleep 代码运行之后,我在 dict_str 中收到此错误。如果我在函数之外声明 msg 并且 msg = None 我没有得到 mydata['lowerpredict'] 和 mydata['Upperpredict']...代码精确错误在 dict_str 中。 有人有解决办法吗?

【问题讨论】:

  • 正如它所说的 - msg 未在全局范围内定义。它只在函数范围内定义。
  • A minimal reproducible example 会有所帮助...您的代码错过了导入语句(可能还有更多?)
  • 请在函数之前全局声明 mes

标签: python raspberry-pi mqtt publish-subscribe


【解决方案1】:

你需要

  1. 在全球范围内声明msg
msg = None

def on_message(client, userdata, message):
    # ...

    global msg
    msg = str(message.payload)

# ...

client = mqtt.Client("P1")
client.on_message= on_message

# ... 

print(msg)
  1. 将访问msg的代码放入函数中:
def on_message(client, userdata, message):
    # ...

    on_message_received(client, userdata, str(message.payload))

def on_message_received(client, userdata, msg):
    print(msg)

    # ...

client = mqtt.Client("P1")
client.on_message= on_message

【讨论】:

  • 即使我在全局范围内声明它,我也会遇到同样的错误
  • edit your question 包括您更新的尝试。
猜你喜欢
  • 1970-01-01
  • 2018-01-24
  • 1970-01-01
  • 2021-04-15
  • 2019-01-26
  • 2021-10-05
  • 2017-08-16
  • 2019-08-18
相关资源
最近更新 更多