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.

0


source to share


1 answer


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

      

+1


source







All Articles