3

我在 Windows XP 上的 PythonPath 有问题,我想知道我是否做错了什么。

假设我有一个包含src目录的项目(使用 Pydev 创建)。在src我有一个名为 的包下,其中有一个以类名common命名的类模块service.pyService

现在说我有另一个项目(也是用 Pydev 创建的),它有一个src目录和一个通用包。在 common 包中,我有一个脚本client.py,用于导入服务。

换句话说,两个独立的磁盘位置,但相同的包。

我注意到即使我将我设置PYTHONPATH为包含两个 src 目录,导入也会失败,除非文件都在同一个目录中。我得到了可怕的找不到模块。

我是否误解了 python 如何解析模块名称?我已经习惯了 Java 和它的类路径地狱。

4

3 回答 3

2

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.

于 2010-07-27T18:39:39.070 回答
1

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

import common1.service as cs
import common2.client as cc
于 2010-07-27T18:22:31.123 回答
1

If you try to import like this:

import src.common.service

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.

于 2010-07-27T18:22:31.510 回答