python install wheel leads to import error

﹥>﹥吖頭↗ 提交于 2021-01-03 08:38:52

问题


I'd like to make a wheel binary distribution, intstall it and then import it in python. My steps are

  • I first create the wheel: python ./my_package/setup.py bdist_wheel
  • I install the wheel: pip install ./dist/*.whl
  • I try to import the package: python -c"import my_package"

This leads to the error: ImportError: No module named 'my_package'

Also, when I do pip list, the my_package is listed. However, when I run which my_packge, nothing is shown.

When I run pip install ./my_package/ everything works as expected.

How would I correctly build and install a wheel?

python version 3.5 pip version 10.1 wheel version 0.31.1

UPDATE:

When I look at the files inside my_package-1.0.0.dist-info, there is an unexpected entry in top_level.txt. It is the name of the folder where I ran python ./my_package/setup.py bdist_wheel in. I believe my setup.py is broken.

UPDATE WITH REGARDS TO ACCEPTED ANSWER: I accepted the answer below. Yet, I think it is better to simply cd into the package directory. Changing to a different directory as suggested below leads to unexpected behavior when using the -d flag, i.e. the target directory where to save the wheel. This would be relative to the directory specified in the setup.py file.


回答1:


If you need to execute the setup script from another directory, ensure you are entering the project dir in the script.

from setuptools import setup

root = os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))
os.chdir(root)

# or using pathlib (Python>=3.4):
import patlib
root = pathlib.Path(__file__).parent
os.chdir(str(root))

setup(...)



回答2:


I had the very same error, but it was due to my setup.py not specifying the entry "packages=setuptools.find_packages()". Everythings builds nicely without that but you can't import anything even though pip shows it to be installed.




回答3:


In my case, in order to solve it I just had to upgrade pip (since Docker installed pip 9).

python3 -m pip install --upgrade pip


来源:https://stackoverflow.com/questions/54145873/python-install-wheel-leads-to-import-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!