在Rhino IronPython 2.7中导入requests模块报错:cannot import idna from encodings
解决IronPython 2.7(Rhino编辑器)导入requests时的idna编码问题
问题描述
在Rhino Python编辑器(基于IronPython 2.7)中手动将requests及依赖模块放入指定lib文件夹后,执行import requests报错:cannot import idna from encodings,报错堆栈如下:
line 16, in , "C:\Users\Thomas.Chu\AppData\Roaming\McNeel\Rhinoceros\7.0\Plug-ins\IronPython (814d908a-e25c-493d-97e9-ee3861957f49)\settings\lib\requests\models.py"
line 135, in , "C:\Users\Thomas.Chu\AppData\Roaming\McNeel\Rhinoceros\7.0\Plug-ins\IronPython (814d908a-e25c-493d-97e9-ee3861957f49)\settings\lib\requests_init_.py"
line 1, in , "C:\Users\Thomas.Chu\AppData\Local\Temp\TempScript.py"
解决方案
- 确认依赖模块完整性:确保lib文件夹中包含完整的
idna模块(requests的核心依赖),且是适配Python 2.7的版本,不要使用Python 3.x的idna包。需将idna的整个文件夹放入lib目录,而非仅部分文件。 - 显式添加模块路径:在脚本开头手动将lib文件夹路径加入
sys.path,确保IronPython优先加载你放置的模块:
import sys lib_path = r"C:\Users\Thomas.Chu\AppData\Roaming\McNeel\Rhinoceros\7.0\Plug-ins\IronPython (814d908a-e25c-493d-97e9-ee3861957f49)\settings\lib" if lib_path not in sys.path: sys.path.append(lib_path) import requests
- 降级requests版本:新版本requests对IronPython 2.7兼容性较差,建议使用requests 2.27.x及以下版本,重新下载对应版本的requests及其依赖(idna、urllib3、chardet等),解压后替换lib文件夹中的现有文件。
- 修改requests的导入逻辑:若上述方法无效,找到报错的
models.py文件(第16行),将from encodings import idna修改为import idna。因为IronPython的系统encodings库中没有idna模块,直接导入lib中的idna即可绕过该错误。
内容的提问来源于stack exchange,提问作者Thomas Chu
相关产品推荐
相关产品推荐

