Python package import - "ImportError: No module named ..."
I know there are many questions about "ImportError: No module named ...", but they seem to seem to boil down to a file __init__.py
or package directory not in $PYTHONPATH
. I have checked both of these problems and my problem is not limited to them.
I have a project that contains protocol buffer definitions. There's a makefile that generates the source as Python, Java or Go. There's a file setup.py
that executes make python
. I ran pip install -e .
in that directory, which generates the source files as expected.
Then I have a separate project where I am trying to use the generated protobuffs.
Let me illustrate my projects:
myproject/ βββ module β βββ __init__.py β βββ module.py βββ main.py myprotos/ βββ Makefile βββ __init__.py βββ my.proto βββ my_pb2.py (generated by the makefile on install) βββ myprotos.egg-info (generated by setup.py) β βββ PKG-INFO β βββ SOURCES.txt β βββ dependency_links.txt β βββ top_level.txt βββ setup.py
The source is setup.py
pretty simple:
import subprocess
import sys
from setuptools import setup
from setuptools.command.install import install
class Install(install):
"""Customized setuptools install command - builds protos on install."""
def run(self):
protoc_command = ["make", "python"]
if subprocess.call(protoc_command) != 0:
sys.exit(-1)
install.run(self)
setup(
name='myprotos',
version='0.0.1',
description='',
install_requires=[],
cmdclass={
'install': Install,
}
)
__init__.py
in myprotos
just contains:
import my_pb2
And then the content myproject/main.py
:
import sys
sys.path.insert(0, '/path/to/myprotos')
import myprotos
Running this code, python main.py
outputs:
Traceback (most recent call last):
File "main.py", line 12, in <module>
import myprotos
ImportError: No module named myprotos
What am I missing here? It looks like it should work, but I am obviously missing something important.
source to share
Let's say you have below structure:
demo_proj
|
myproject/
βββ module
β βββ __init__.py
β βββ module.py
βββ main.py
myprotos/
βββ Makefile
βββ __init__.py
βββ my.proto
βββ my_pb2.py
βββ myprotos.egg-info
β βββ PKG-INFO
β βββ SOURCES.txt
β βββ dependency_links.txt
β βββ top_level.txt
βββ setup.py
Code in main.py:
import sys
sys.path.insert(0, '/path/to/demo_proj')
import myprotos
source to share