为什么我不能从Python 3.4中的PYTHONPATH导入模块?

时间:2015-03-20 05:44:19

标签: python python-3.4 python-import python-module

我在/u/home/j/joelfred/python-dev-modules安装了一个软件包。它看起来像:

/a
    __init__.py
    b.py

b.py的来源只是:

def hello():
    print('hi yourself')

对于__init__.py

import b

首先,我确保我在我的主目录中,并设置我的PYTHONPATH:

$ cd
$ export PYTHONPATH=/u/home/j/joelfred/python-dev-modules/

然后我运行python3

$ python3
Python 3.4.3 (default, Mar 18 2015, 17:28:34) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-11)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/u/home/j/joelfred/python-dev-modules/a/__init__.py", line 1, in <module>
    import b
ImportError: No module named 'b'

好的,这很奇怪。但是,如果我将__init__.py更改为空白:

$ python3
Python 3.4.3 (default, Mar 18 2015, 17:28:34) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-11)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import a.b as b
>>> b.hello()
hi yourself
>>> 

到底是怎么回事?

1 个答案:

答案 0 :(得分:4)

在Python 3中,所有导入都是绝对的。除非import b本身是b上提供的顶级模块/包,否则您无法sys.path。如果要从b内导入a,请使用显式相对导入:

from . import b