![](/img/trans.png)
[英]TypeError: create() takes 2 positional arguments but 4 were given
[英]TypeError: publish() takes 2 positional arguments but 3 were given
因此,我正在使用MQTT Publisher,並希望創建一個pub類。 我在這里找到了類似的問題,但我不知道它如何轉化為我的問題。
這是我的代碼:
def send_on_sensor(q, topic, delay, pub):
while q.empty is not True:
payload = json.dumps(q.get())
pub.publish(payload)
time.sleep(delay)
class Pub:
def __init__(self, MQTT_BROKER, MQTT_TOPIC):
self.MQTT_BROKER = MQTT_BROKER
self.MQTT_TOPIC = MQTT_TOPIC
self.mqttc = mqtt.Client()
self.mqttc.on_connect = self.on_connect
self.mqttc.publish = self.publish
# Connect automatically on the creation of the object, but disconnect manually
self.connect()
def on_connect(self, client, userdata, flags, rc):
print("Connecting to {}. Connection returned result: {}".format(self.MQTT_BROKER, rc))
self.mqttc.subscribe(self.MQTT_TOPIC)
def publish(self, MQTT_MSG):
self.mqttc.publish(self.MQTT_TOPIC, MQTT_MSG)
def connect(self):
self.mqttc.connect(self.MQTT_BROKER)
def disconnect(self):
self.mqttc.disconnect()
我收到此錯誤:
Exception in thread Thread-4:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 917, in _bootstrap_inner
self.run()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 865, in run
self._target(*self._args, **self._kwargs)
File "/Users//PycharmProjects//V3_multiTops/mt_GenPub.py", line 76, in send_on_sensor
pub.publish(payload)
File "/Users//PycharmProjects//V3_multiTops/mt_GenPub.py", line 129, in publish
self.mqttc.publish(self.MQTT_TOPIC, MQTT_MSG)
TypeError: publish() takes 2 positional arguments but 3 were given
這里的問題到底是什么?如何解決?
您要將兩個參數傳遞給publish():
self.mqttc.publish(self.MQTT_TOPIC, MQTT_MSG)
但是該函數被定義為僅接受一個參數(除了self
,它會自動傳遞):
def publish(self, MQTT_MSG):
為什么要傳遞MQTT_TOPIC
?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.