python相对导入示例代码

2024-05-15 21:01:24 发布

您现在位置:Python中文网/ 问答频道 /正文

Possible Duplicate:
How to properly use relative or absolute imports in Python modules?

我有这个文件布局,如本例所示: (在此处下载:http://www.mediafire.com/?oug42nzvxrvoms4http://www.python.org/dev/peps/pep-0328/#guido-s-decision

moduleX包含:

from .moduleY import spam
from .moduleY import spam as ham
from . import moduleY
from ..subpackage1 import moduleY
from ..subpackage2.moduleZ import eggs
from ..moduleA import foo
from ...package import bar
from ...sys import path

这就是发生的事情:

C:\package\subpackage1>python moduleX.py
Traceback (most recent call last):
  File "moduleX.py", line 1, in <module>
    from .moduleY import spam
ValueError: Attempted relative import in non-package

我有Python2.7.2。我有

__init__.py

每个目录中的文件。 为什么这个代码不起作用?


Tags: 文件infrompyimporthttppackagewww
1条回答
网友
1楼 · 发布于 2024-05-15 21:01:24

从文档中:

你可以看到:

Relative imports use a module's name attribute to determine that module's position in the package hierarchy. If the module's name does not contain any package information (e.g. it is set to 'main') then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.

通过将其作为python moduleX.py运行,您正是在执行上述操作。相反,请尝试以下操作:

python -m package.subpackage1.moduleX

这将导入moduleX并将顶层放在package。从层次结构的顶部运行:

package/
    __init__.py
    subpackage1/
        __init__.py
        moduleX.py
        moduleY.py
    subpackage2/
        __init__.py
        moduleZ.py
    moduleA.py

即,在您的情况下,直接从c:\

c:\>python -m package.subpackage1.moduleX

注意一件事-moduleX.py中的导入如下:

from .moduleY import spam
from .moduleY import spam as ham
from . import moduleY
from ..subpackage1 import moduleY
from ..subpackage2.moduleZ import eggs
from ..moduleA import foo
from ...package import bar
from ...sys import path

倒数第二个:

from ...package import bar

要求根文件夹(c:\)是一个包(即have__init__.py)。此外,它还需要在package\__init__.py中定义的bar变量,而该变量当前不存在(因此将bar = 'bar!'放在那里进行测试)。它还要求您向上一级-因此您必须将package文件夹放在另一个文件夹中(这样您最终会得到c:\toppackage\package),然后运行c:\python -m toppackage.package.subpackage1.moduleX

对于这一行:

from ...sys import path

在上面的PEP 328链接中有一个注释:

Note that while that last case is legal, it is certainly discouraged ("insane" was the word Guido used).

另请参阅其他可能有帮助的soq:

希望这有帮助。

相关问题 更多 >