ImportError:没有名为mqtt.client的模块错误[paho-mqtt]

时间:2019-05-09 23:43:07

标签: python pycharm paho

我正在尝试在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出现在我已安装的软件包中。

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

谢谢。

3 个答案:

答案 0 :(得分:1)

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

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

pip安装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

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

答案 1 :(得分:0)

可能的原因是

库“ paho”已安装(默认情况下)在文件夹“ /home/user/.local/lib/python2.7/site-packages”中 但 “ python”在文件夹“ /usr/local/lib/python2.7/dist-packages”中搜索此库。 可以从here引用dist和site软件包之间的区别。

ln命令用于在文件之间创建链接。因此,该文件是从script.py目录中引用的。

答案 2 :(得分:0)

通过查看naff和Roshan的回答,就我而言,该软件包已安装在此位置的蟒蛇3.7的Anaconda版本中

  • /home/user/anaconda3/lib/python3.7/site-packages/paho

我使用了这个脚本:

  • sudo cp -r /home/user/anaconda3/lib/python3.7/site-packages/paho /home/user/.local/lib/python3.7/site-packages /

它解决了我的问题,希望对您有所帮助。