属性错误:“NoneType”对象没有属性“subscribe”



我正在尝试使用代码向经纪人发送帖子,但我遇到了一些问题。代码如下:

import paho.mqtt.client as mqtt
def on_connect(self, client, userdata, rc):
    if rc==0:
    print("successful connection")
    client.subscribe("HelloWorld")
else:
    print("connection fail") #the subscriber will not receive the message
def on_message (client, userdata, msg):
print( str(msg.payload.decode('UTF-8'))) #Post Posted
client= mqtt.Client()
client.on_connect = on_connect #Create the "client" object
client.on_message = on_message
client.username_pw_set("TypeUser",typePassaword) # I omitted username and password
client.connect('TypeURLBroker',TypePort) #Broker Online. 1º Termo: Url do broker; 2º Termo: Port
client.loop_start()
while 0==0:
mymsg='Hello World'
client.publish(topic='HelloWorld/', payload=mymsg)

出现了一些错误,我不知道解决它们。我需要一点帮助。

错误列表:

successful connection
Exception in thread Thread-6:
Traceback (most recent call last):
File "C:UsersfvsAppDataLocalProgramsPythonPython35libthreading.py", line 914, in _bootstrap_inner
    self.run()
  File "C:UsersfvsAppDataLocalProgramsPythonPython35libthreading.py", line 862, in run
    self._target(*self._args, **self._kwargs)
  File "C:UsersfvsAppDataLocalProgramsPythonPython35libsite-packagespahomqttclient.py", line 2606, in _thread_main
    self.loop_forever(retry_first_connection=True)
  File "C:UsersfvsAppDataLocalProgramsPythonPython35libsite-packagespahomqttclient.py", line 1470, in loop_forever
    rc = self.loop(timeout, max_packets)
  File "C:UsersfvsAppDataLocalProgramsPythonPython35libsite-packagespahomqttclient.py", line 995, in loop
    rc = self.loop_read(max_packets)
  File "C:UsersfvsAppDataLocalProgramsPythonPython35libsite-packagespahomqttclient.py", line 1273, in loop_read
    rc = self._packet_read()
  File "C:UsersfvsAppDataLocalProgramsPythonPython35libsite-packagespahomqttclient.py", line 1838, in _packet_read
    rc = self._packet_handle()
  File "C:UsersfvsAppDataLocalProgramsPythonPython35libsite-packagespahomqttclient.py", line 2291, in _packet_handle
    return self._handle_connack()
  File "C:UsersfvsAppDataLocalProgramsPythonPython35libsite-packagespahomqttclient.py", line 2349, in _handle_connack
    self.on_connect(self, self._userdata, flags_dict, result)
  File "C:/Users/fvs/PycharmProjects/HelloWorld.py", line 6, in on_connect
    client.subscribe("HelloWorld")
AttributeError: 'NoneType' object has no attribute 'subscribe'

根据文档on_connect应该有以下签名

on_connect(client, userdata, flags, rc)

您尝试使用第二个位置参数,这实际上userdata,而不是client。尝试

def on_connect(client, userdata, flags, rc):
    if rc==0:
        print("successful connection")
        client.subscribe("HelloWorld")
    else:
        print("connection fail") #the subscriber will not receive the message

最新更新