本文介绍了导入Python程序包-"ImportError:未命名模块..."的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道关于"ImportError:没有名为...的模块"的问题很多,但是它们通常可以归结为没有__init__.py文件或不在$PYTHONPATH中的软件包目录.我已经检查了这两个问题,而我的问题还不止于此.

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. I've checked both of those issues and my issue is not down to them.

我有一个包含协议缓冲区定义的项目.有一个生成文件,其生成源为Python,Java或Go.有一个执行make pythonsetup.py文件.我已经在该目录中运行pip install -e .,该目录将按预期生成源文件.

I have a project which contains protocol buffer definitions. There's a makefile which generates the source as Python, Java or Go. There's a setup.py file which executes make python. I've run pip install -e . in this directory which generates the source files as expected.

然后我有一个单独的项目,试图在此使用生成的protobuf.

I then have a separate project where I'm trying to use the generated protobufs.

让我说明一下我的项目:

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

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,
    }
)

myprotos中的__init__.py仅包含:

import my_pb2

然后myproject/main.py的内容是:

import sys
sys.path.insert(0, '/path/to/myprotos')

import myprotos

运行此代码,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.

推荐答案

假设您具有以下结构:

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

main.py中的代码:

import sys
sys.path.insert(0, '/path/to/demo_proj')

import myprotos

这篇关于导入Python程序包-"ImportError:未命名模块..."的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-12 19:02