You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Azure IoT Edge SDK时持续出现‘azure’模块未找到错误怎么办?

问题

已按照要求使用pip在conda环境中安装了运行Azure IoT Edge SDK Python文件所需的pypi包azure-iot-device,但仍无法正常运行。甚至尝试过安装2020年已废弃的azure包,问题依旧。始终遇到ModuleNotFoundError错误,但参考的所有演示案例操作步骤相同却未出现该问题。

错误信息

Traceback (most recent call last):
  File "/Users/.../tempCodeRunnerFile.python", line 14, in <module>
    from azure.iot.device.aio import IoTHubDeviceClient
ModuleNotFoundError: No module named 'azure'

运行代码

from azure.iot.device.aio import IoTHubDeviceClient
from azure.iot.device import Message

# The device connection string to authenticate the device with your IoT hub.
CONNECTION_STRING = ****

MESSAGE_TIMEOUT = 10000

# Define the JSON message to send to IoT Hub.
TEMPERATURE = 20.0
HUMIDITY = 60
MSG_TXT = "{\"temperature\": %.2f,\"humidity\": %.2f}"

# Temperature threshold for alerting
TEMP_ALERT_THRESHOLD = 30


async def main():
    try:
        client = IoTHubDeviceClient.create_from_connection_string(CONNECTION_STRING)
        await client.connect()

        print("IoT Hub device sending periodic messages, press Ctrl-C to exit")

        while True:
            # Build the message with simulated telemetry values.
            temperature = TEMPERATURE + (random.random() * 15)
            humidity = HUMIDITY + (random.random() * 20)
            msg_txt_formatted = MSG_TXT % (temperature, humidity)
            message = Message(msg_txt_formatted)

            # Add standard message properties
            message.message_id = uuid.uuid4()
            message.content_encoding = "utf-8"
            message.content_type = "application/json"

            # Add a custom application property to the message.
            # An IoT hub can filter on these properties without access to the message body.
            prop_map = message.custom_properties
            prop_map["temperatureAlert"] = ("true" if temperature > TEMP_ALERT_THRESHOLD else "false")

            # Send the message.
            print("Sending message: %s" % message.data)
            try:
                await client.send_message(message)
            except Exception as ex:
                print("Error sending message from device: {}".format(ex))
            await asyncio.sleep(1)

    except Exception as iothub_error:
        print("Unexpected error %s from IoTHub" % iothub_error)
        return
    except asyncio.CancelledError:
        await client.shutdown()
        print('Shutting down device client')

if __name__ == '__main__':
    print("IoT Hub simulated device")
    print("Press Ctrl-C to exit")
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        print('Keyboard Interrupt - sample stopped')
解决方案
  • 确认conda环境激活状态
    运行代码前必须确保目标conda环境已激活。执行以下命令检查当前环境:

    conda info --envs
    

    若未激活目标环境,执行:

    conda activate <你的环境名称>
    

    激活后再执行pip install azure-iot-device,确保包安装在当前激活环境中。

  • 检查pip与conda环境的关联
    部分情况下,系统全局pip会覆盖conda环境的pip,导致包安装到全局而非目标环境。执行以下命令确认当前pip所属环境:

    which pip
    

    输出路径应包含你的conda环境目录(如/Users/xxx/miniconda3/envs/<环境名>/bin/pip)。若路径不对,改用conda环境内的pip安装:

    python -m pip install azure-iot-device
    
  • 验证包是否正确安装
    激活环境后,执行以下命令查看已安装包:

    pip list | grep azure-iot-device
    

    若能看到azure-iot-device及其版本号,说明安装成功;若未找到,重新执行安装命令并检查是否有报错。

  • 检查代码运行环境
    确保运行代码的Python解释器是conda环境内的版本。执行:

    which python
    

    路径需与conda环境一致。若使用IDE(如VS Code),需在设置中指定conda环境的Python解释器。

  • 移除废弃的azure包
    废弃的azure包与azure-iot-device可能存在冲突,执行以下命令卸载:

    pip uninstall azure -y
    

    之后重新安装azure-iot-device:

    pip install azure-iot-device --force-reinstall
    
  • 补充代码缺失的依赖导入
    你的代码中用到了random、uuid和asyncio模块,需在代码顶部添加导入语句:

    import random
    import uuid
    import asyncio
    

内容的提问来源于stack exchange,提问作者Kiki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 03:01:07