【问题标题】:Import module from sibling package with absolute import使用绝对导入从同级包导入模块
【发布时间】:2014-05-02 10:14:13
【问题描述】:

如何使用来自同级包的模块的绝对导入?

包文件结构:

.
├── a
│   ├── __init__.py
│   └── modulea.py
├── b
│   ├── __init__.py
│   ├── moduleb.py
├── __init__.py
└── test.py

文件 test.py 和 a/modulea.py:

from b.moduleb import f

if __name__ == '__main__':
    f()

文件 b/moduleb.py:

def f():
    print('hello')

这行得通:

% python test.py 
hello

这不是:

% python a/modulea.py 
Traceback (most recent call last):
  File "a/modulea.py", line 1, in <module>
    from b.moduleb import f
ImportError: No module named 'b'

据我所知,它应该可以工作:http://docs.python.org/3.3/tutorial/modules.html#intra-package-references。我错过了什么吗?

【问题讨论】:

    标签: python python-3.x python-import


    【解决方案1】:

    使用python -ma.modulea

    运行 python a/modulea.py 会将 a 目录添加到 sys.path 而不是父目录 (.)。

    不要直接从 Python 包内部运行脚本。见Traps for the Unwary

    【讨论】:

      【解决方案2】:

      无论. 是什么,您都需要一个__init__.py

      【讨论】:

      • 对我不起作用:pastebin.com/KvHBAbMY。 test/a/modulea.py 中的 import 语句应该是什么样的?
      • 你所拥有的应该可以工作。可以import sys ; print(sys.path)吗?
      • 在./test:% echo 'import sys ; print(sys.path)' &gt; test2.py; python test2.py ['./test', '/usr/lib/python33.zip', '/usr/lib/python3.3', '/usr/lib/python3.3/plat-linux', '/usr/lib/python3.3/lib-dynload', '/usr/lib/python3.3/site-packages']
      • 嗯,好的。将 . 添加到 PYTHONPATH 环境变量中。
      • 你可能想要制作一个合适的 setup.py 和 python setup.py develop
      猜你喜欢
      • 2014-06-25
      • 2015-08-21
      • 2021-11-08
      • 2021-02-05
      • 1970-01-01
      • 1970-01-01
      • 2015-12-22
      • 2010-10-17
      相关资源
      最近更新 更多