[英]Importing Python package - “ImportError: No module named…”
I know there are a lot of questions about "ImportError: No module named..." but they ususally seem to boil down to no __init__.py
file or the package directory not in $PYTHONPATH
. 我知道关于“ ImportError:未命名的模块...”有很多问题,但是它们通常似乎可以归结为无
__init__.py
文件或$PYTHONPATH
没有的软件包目录。 I've checked both of those issues and my issue is not down to them. 我已经检查了这两个问题,但我的问题还不止于这些。
I have a project which contains protocol buffer definitions. 我有一个包含协议缓冲区定义的项目。 There's a makefile which generates the source as Python, Java or Go.
有一个生成文件,其生成源为Python,Java或Go。 There's a
setup.py
file which executes make python
. 有一个
setup.py
文件,它执行make python
。 I've run pip install -e .
我已经运行了
pip install -e .
in this directory which generates the source files as expected. 在此目录中,该目录将按预期生成源文件。
I then have a separate project where I'm trying to use the generated protobufs. 然后,我有一个单独的项目,尝试使用生成的protobuf。
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 of setup.py
is pretty simple: setup.py
的源非常简单:
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,
}
)
The __init__.py
in myprotos
simply contains: myprotos
的__init__.py
仅包含:
import my_pb2
And then the contents of myproject/main.py
is: 然后
myproject/main.py
的内容是:
import sys
sys.path.insert(0, '/path/to/myprotos')
import myprotos
Running this code, python main.py
outputs: 运行以下代码,
python main.py
输出:
Traceback (most recent call last):
File "main.py", line 12, in <module>
import myprotos
ImportError: No module named myprotos
What have I missed here? 我在这里错过了什么? It seems like this should work but I clearly haven't understood something crucial.
看来这应该可行,但是我显然还不了解一些关键的内容。
Let 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: main.py中的代码:
import sys
sys.path.insert(0, '/path/to/demo_proj')
import myprotos
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.