AttributeError:'NoneType'对象没有属性'subscribe'

时间:2017-10-28 17:31:18

标签: python

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

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:\Users\fvs\AppData\Local\Programs\Python\Python35\lib\threading.py", line 914, in _bootstrap_inner
    self.run()
  File "C:\Users\fvs\AppData\Local\Programs\Python\Python35\lib\threading.py", line 862, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\fvs\AppData\Local\Programs\Python\Python35\lib\site-packages\paho\mqtt\client.py", line 2606, in _thread_main
    self.loop_forever(retry_first_connection=True)
  File "C:\Users\fvs\AppData\Local\Programs\Python\Python35\lib\site-packages\paho\mqtt\client.py", line 1470, in loop_forever
    rc = self.loop(timeout, max_packets)
  File "C:\Users\fvs\AppData\Local\Programs\Python\Python35\lib\site-packages\paho\mqtt\client.py", line 995, in loop
    rc = self.loop_read(max_packets)
  File "C:\Users\fvs\AppData\Local\Programs\Python\Python35\lib\site-packages\paho\mqtt\client.py", line 1273, in loop_read
    rc = self._packet_read()
  File "C:\Users\fvs\AppData\Local\Programs\Python\Python35\lib\site-packages\paho\mqtt\client.py", line 1838, in _packet_read
    rc = self._packet_handle()
  File "C:\Users\fvs\AppData\Local\Programs\Python\Python35\lib\site-packages\paho\mqtt\client.py", line 2291, in _packet_handle
    return self._handle_connack()
  File "C:\Users\fvs\AppData\Local\Programs\Python\Python35\lib\site-packages\paho\mqtt\client.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'

1 个答案:

答案 0 :(得分:1)

根据docs 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