问题
I am trying to import a zip file packaged with numpy.
I have zipped numpy into packages.zip
. However while using the zip file I am getting the following import error.
> python
Python 2.7.9 (default, Jan 7 2015, 11:49:12)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.56)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path.insert(0, 'packages.zip')
>>> import numpy
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "packages.zip/numpy/__init__.py", line 180, in <module>
File "packages.zip/numpy/add_newdocs.py", line 13, in <module>
File "packages.zip/numpy/lib/__init__.py", line 8, in <module>
File "packages.zip/numpy/lib/type_check.py", line 11, in <module>
File "packages.zip/numpy/core/__init__.py", line 14, in <module>
ImportError: cannot import name multiarray
>>>
After checking numpy/core I found __init__.py
is trying to import multiarray.so
file.
How can I resolve this error ? Thanks
回答1:
Operating systems don't recognize .so files inside of .zip files. But python "eggs" can extract extension modules on import so that the operating system can see and load them. See setuptools Extension Import Wrappers for details.
I went to numpy on pypi and found its source on sourceforge. After downloading and extracting the source, I changed to the source directory and ran python3 setup.py bdist_egg
and it generated an "egg" file (which is a .zip file with a predefined structure python can use at import). After changing to the "dist" directory, the code works:
>>> import sys
>>> sys.path.insert(0, 'numpy-1.11.0-py3.4-linux-x86_64.egg')
>>> import numpy
>>> numpy.__file__
'numpy-1.11.0-py3.4-linux-x86_64.egg/numpy/__init__.py'
Notice that the "egg" is platform specific (I used python 3.4 on linux x86_64) so you want to run setup.py
on a system close to the system you target for deployment.
"egg" is the old package format and "wheel" is the new format but eggs have the advantage that you can run extension modules directly from the .zip file while wheels need to be installed. From the Wheel vs Egg page:
Wheel is a distribution format, i.e a packaging format. [1] Egg was both a distribution format and a runtime installation format (if left zipped), and was designed to be importable.
If you don't mind installing numpy
, you can use one of the prebuilt wheels on pypi or even just pip install numpy
if you have access to the internet. But if you want to run from the .zip file, stick with eggs.
来源:https://stackoverflow.com/questions/36756235/python-import-error-with-zip