PYTHONPATH 具有重叠包结构的地狱
我在 Windows XP 上使用 PythonPath 时遇到问题,我想知道我是否做错了什么。
假设我有一个项目(使用 Pydev 创建),它有一个 src 目录。在 src
下,我有一个名为 common
的包,其中有一个名为 service.py
的类模块,其类名为 Service
现在假设我有另一个项目(也是使用 Pydev 创建的),其中有一个 src 目录和一个公共包。在公共包中,我有一个导入服务的脚本 client.py
。
换句话说,两个独立的磁盘位置,但相同的包。
我注意到,即使我将 PYTHONPATH 设置为包含两个 src 目录,导入也会失败,除非文件都位于同一目录中。我得到了可怕的“找不到模块”。
我是否误解了 python 如何解析模块名称?我已经习惯了 Java 和它的类路径地狱。
I'm having problems with my PythonPath on windows XP, and I'm wondering if I'm doing something wrong.
Say that I have a project (created with Pydev) that has an src
directory. Under src
I have a single package, named common
, and in it a single class module, named service.py
with a class name Service
Say now that I have another project (also created with Pydev) with an src
directory and a common package. In the common package, I have a single script, client.py
, that imports service.
So in other words, two separate disk locations, but same package.
I've noticed that even if I set my PYTHONPATH
to include both src directories, the import fails unless the files are both in the same directory. I get the dreaded no module found.
Am I misunderstanding how python resolves module names? I'm used to Java and its classpath hell.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为在 Python 中,最好通过为每个包提供唯一的名称来避免这个问题。不要将这两个包命名为
common
。然后你可以用类似的东西导入两者I think in Python you are best off avoiding this problem by providing each package with a unique name. Don't name both packages
common
. Then you can import both with something like如果您确实必须有这样的拆分包,请阅读模块级别属性 __path__。
简而言之,将“src”目录之一设为主目录,并给它一个 __init__.py,将其他“src”的路径附加到 __path__ 列表中。现在,Python 在查找“src”的子模块时将同时查找这两个位置。
但从长远来看,我真的不建议这样做。它有点脆,如果你移动东西就会破裂。
If you really must have a split package like this, read up on the module level attribute __path__.
In short, make one of the 'src' directories the main one, and give it an __init__.py that appends the path of other 'src' to the __path__ list. Python will now look in both places when looking up submodules of 'src'.
I really don't recommend this for the long term though. It is kind of brittle and breaks if you move things around.
如果您尝试像这样导入:
Python 将在 Python 路径中查找名为“src”的目录(或 Egg 等)。一旦找到“src”,它就不会考虑另一个。如果第一个“src”目录中没有 common 和 service,那么即使路径中的另一个“src”目录确实有这些内容,您也会收到一个 ImportError 错误。
If you try to import like this:
Python will look on the Python path for a directory named "src" (or an egg, etc). Once it finds "src", it will not consider another one. If the first "src" doesn't have common and service inside it, then you will get an ImportError, even if another "src" directory in the path does have those things.