为什么在 Python 中不允许从 ZIP 文件导入 *.so 文件?
文档(https://docs.python.org/2/library/zipimport.html)非常清楚:
Any files may be present in the ZIP archive, but only files .py and .py[co] are available for import. ZIP import of dynamic modules (.pyd, .so) is disallowed.
但是文档没有说明这种奇怪限制的任何原因。是因为在 Python 中通常不鼓励从 ZIP 文件导入吗?还是出于安全原因?如果有,是哪些?有官方说法吗?
请您参考如下方法:
来自 PEP 273, Subdirectory Equivalence :
You can't satisfy dynamic modules from a zip file. Dynamic modules have extensions like
.dll,.pyd, and.so. They are operating system dependent, and probably can't be loaded except from a file. It might be possible to extract the dynamic module from the zip file, write it to a plain file and load it. But that would mean creating temporary files, and dealing with all thedynload_*.c, and that's probably not a good idea.
我的解释是,做出这个决定是为了避免让解释器提取动态模块并将其保存到磁盘,因为操作系统的动态库设施不允许从 zip 中加载(参见 Windows 的 LoadLibraryA 和Linux 的 dlopen )。
虽然看起来这在技术上并非不可能,但实现此功能的工作可能不值得的一个原因是这些库的平台依赖性。包含动态模块的 .zip 如果它是从 64 位环境创建的,则它可能无法在 32 位环境中工作,并且在 32 位环境中可能无法工作Linux 如果它是在 Windows 中创建的。禁止在 .zip 中使用动态模块可能是一个有意识的决定,以确保包含 Python 模块的 .zip 可以跨平台工作。
