'python install wheel leads to import error

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.



Solution 1:[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(...)

Solution 2:[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.

Solution 3:[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

Solution 4:[4]

I have experienced the same situation, maybe not for the same reason, here just for reference. The package name should not contain the dash "-", there's no error pop out, but after installing your wheel, though it is shown in pip list, you can't find that package.

/src/your-package-name # should not

/src/your_package_name # should like this

In the setup.py, you can use the name with dash "-" without limitation:

setuptools.setup(
name="instrument-lab",
...

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 hoefling
Solution 2 wkirgsn
Solution 3 thethiny
Solution 4 Max