首页 > 解决方案 > ImportError:没有名为 mqtt.client 的模块错误 [paho-mqtt]

问题描述

我正在尝试在 python 项目中使用 paho-mqtt,我使用 pycharm 作为我的 IDE。我安装了 paho-mqtt 使用:pip install paho-mqtt,但似乎有些不对劲。因为当我部署以下脚本时:

import paho.mqtt.client as mqtt

# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))

    # Subscribing in on_connect() means that if we lose the connection and
    # reconnect then subscriptions will be renewed.
    client.subscribe("/test")


# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
    print(msg.topic+" "+str(msg.payload))

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

client.connect("localhost", 1883, 60)

# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.
client.loop_forever()

给我以下错误:

/usr/bin/python2.7 /home/user/PycharmProjects/untitled/MQTT/paho.py
Traceback (most recent call last):
  File "/home/user/PycharmProjects/untitled/MQTT/paho.py", line 1, in <module>
    import paho.mqtt.client as mqtt
  File "/home/user/PycharmProjects/untitled/MQTT/paho.py", line 1, in <module>
    import paho.mqtt.client as mqtt
ImportError: No module named mqtt.client

Process finished with exit code 1

paho-mqtt 出现在我已安装软件包的一部分。

有人已经遇到过这个问题并解决了吗?

谢谢。

标签: pythonpycharmpaho

解决方案


我以以下问题为例解决了这个问题:https ://github.com/shivasiddharth/GassistPi/issues/725

  1. 使用以下命令安装 paho-mqtt:

点安装 paho-mqtt

  1. 在 script.py 目录中,我运行了以下命令:

    • ln -s /home/user/.local/lib/python2.7/site-packages/paho paho
    • ln -s /home/user/.local/lib/python2.7/site-packages/paho_mqtt-1.4.0.dist-info paho_mqtt-1.4.0.dist-info

这可能不是解决问题的正确方法,但没有其他方法有效。


推荐阅读