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

简易天气应用运行报错:ModuleNotFoundError: No module named 'urllib3.packages.six.moves'

解决ModuleNotFoundError: No module named 'urllib3.packages.six.moves'问题

你的天气查询代码逻辑本身无问题,报错源于urllib3与six的依赖关联异常,以下是针对性解决步骤:

  • 确认Python环境一致性
    多版本Python混用常导致安装包与运行解释器不匹配:

    • 执行pip --version查看当前pip对应的Python路径
    • 执行python --version查看代码运行的Python路径,确保两者完全一致
    • 推荐用虚拟环境隔离依赖:
      # 创建虚拟环境
      python -m venv weather_env
      # Windows激活环境
      weather_env\Scripts\activate
      # Linux/macOS激活环境
      source weather_env/bin/activate
      # 安装依赖
      pip install requests six urllib3
      
  • 强制安装兼容版本的依赖包
    部分新版本urllib3可能移除了urllib3.packages.six的内置引用,尝试安装验证过的兼容版本:

    pip uninstall -y requests six urllib3
    pip install requests==2.31.0 urllib3==2.0.7 six==1.16.0
    
  • 修复urllib3的包结构
    手动检查urllib3的packages目录是否缺失six模块:

    1. 执行python -c "import site; print(site.getsitepackages())"获取site-packages路径
    2. 进入该路径下的urllib3/packages目录,确认是否存在six文件夹
    3. 若缺失,将同级目录下的six文件夹复制到urllib3/packages中
  • 清理缓存后重装
    缓存损坏可能导致安装异常,清理后重新安装:

    pip cache purge
    pip install --no-cache-dir requests six urllib3
    

你的代码如下:

import requests
import json


def get_weather(city, api_key):
    base_url = "http://api.openweathermap.org/data/2.5/weather?"


    complete_url = base_url + "q=" + city + "&appid=" + api_key + "&units=metric"

    response = requests.get(complete_url)
    data = response.json()

    if data["cod"] != "404":
        main = data["main"]
        wind = data["wind"]
        weather = data["weather"][0]
        temperature = main["temp"]
        humidity = main["humidity"]
        weather_description = weather["description"]
        wind_speed = wind["speed"]

        print(f"City: {city}")
        print(f"Temperature: {temperature}°C")
        print(f"Humidity: {humidity}%")
        print(f"Weather: {weather_description.capitalize()}")
        print(f"Wind Speed: {wind_speed} m/s")

    else:
        print(f"City {city} not found. Please enter a valid city name.")


if __name__ == "__main__":
    api_key = "5a249ac961fe0222f884ded14818c13e"
    city = input("Enter city name: ")
    get_weather(city, api_key)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 13:17:33