我正在尝试导入另一个文件夹中的包,它在python3.4中运行得非常好。例如:文件存在于库文件夹中。
user> python
Python 3.4.1 (default, Nov 12 2014, 13:34:29)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from libraries.controller_utils import *
>>>
但是,当我打开一个新的shell并使用Python2.7时:
user> python
Python 2.7.4 (default, Jun 1 2015, 10:35:58)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-55)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from libraries.controller_utils import *
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named libraries.controller_utils
>>>
我尝试将条目添加到sys.path
中,但这并没有帮助。我读了一个类似的问题这里,但解决方案也没有帮助我,因为我尝试了相对和绝对导入。请指点。
编辑:目录结构为~/tests/libraries/controller_utils.py
。我正在测试目录中执行这些命令。
编辑:我添加了sys.path条目,如下所示,但它仍然不识别它。请注意,该错误发生在2.7,但在3.4上工作非常好
user> cd ~/tests/
user> ls
__pycache__ backups inputs libraries openflow.py test_flow.py
user> ls libraries/
__pycache__ controller_utils.py general_utils.py general_utils.pyc tc_name_list.py test_case_utils.py
user> python
Python 2.7.4 (default, Jun 1 2015, 10:35:58)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-55)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from libraries.controller_utils import *
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named libraries.controller_utils
>>> import sys
>>> sys.path.append('libraries/')
>>> from libraries.controller_utils import *
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named libraries.controller_utils
发布于 2015-09-18 10:09:08
您的libraries
包缺少__init__.py
文件。您可以使用该名称创建一个空文件,然后:
from libraries.controller_utils import *
应该行得通。
或者,如果不想将libraries
转换为包,则应该将其路径添加到sys.path
并导入controller_utils
import sys
sys.path.append('libraries/')
from controller_utils import *
请注意,错误是由于python2要求__init__.py
从包中导入,而python3.3+提供命名空间包 (参见PEP420)。这就是为什么在python3.4中导入不会失败的原因。
如果希望代码以同样的方式在python2和python3中工作,则应该始终将__init__.py
文件添加到包中,并在文件中使用from __future__ import absolute_import
。
发布于 2015-09-18 09:56:46
见佩普0404。
在Python 3中,包中的隐式相对导入不再可用--只支持绝对导入和显式相对导入。此外,star导入(例如从x import *)仅允许在模块级代码中进行。
如果libraries
位于同一目录中,这将避免与安装在系统级别的包发生冲突。这将是一个隐含的相对进口。
您应该能够使用..
导航到模块的正确位置,如:
from ..libraries.controller_utils import *
# or, depending of you directory structure
# put as many dots as directories you need to get out of
from ....common.libraries.controller_utils import *
但你的案子似乎和明星的进口有关。在Python3中,只能在文件的顶层使用星型导入( star,from x import *
),即不能在函数或类定义中使用。
https://stackoverflow.com/questions/32658058
复制