python路径中的Zip未按预期工作

2024-05-13 01:51:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一个名为msgpack.zip的zip文件中有msgpack模块。在

当我将zip文件添加到python路径时,我能够导入模块,但不能导入它的编译部分:

>>> import sys
>>> sys.path.insert(0, 'msgpack.egg')
>>> import msgpack
>>> from msgpack._packer import Packer
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named 'msgpack._packer'
>>>

但是,如果我将zip文件解压缩到我所在的同一个目录,那么它就可以工作了:

验证我没有通过其他方式安装msgpack。。。在

^{pr2}$

请注意,我没有msgpack到我的计算机上的任何其他路径。如果我从我正在工作的目录中删除msgpack文件夹,我会在import msgpack上得到一个导入错误。在

所以问题是,为什么导入zip中包含的模块不会导入库的编译部分,但是如果我将zip解压到一个目录中,然后尝试导入它,它们就会被导入?


Tags: 模块文件pathfromimport路径目录egg
1条回答
网友
1楼 · 发布于 2024-05-13 01:51:09

根据documentation

If the resource is in an archive distribution (such as a zipped egg), it will be extracted to a cache directory

默认缓存目录由函数get_default_cache()决定。doc上写着

Determine the default cache location for extracting resources from zipped eggs. This routine returns the PYTHON_EGG_CACHE environment variable, if set. Otherwise, on Windows, it returns a "Python-Eggs" subdirectory of the user's "Application Data" directory. On all other systems, it returns os.path.expanduser("~/.python-eggs") if PYTHON_EGG_CACHE is not set.

所以,我猜您的eggs缓存文件夹有问题。在

相关问题 更多 >