Vin*_*Pai 2 python python-2.7 python-3.4
我正在尝试导入另一个文件夹中存在的包,它在python 3.4中运行得非常好.例如:文件存在于libraries文件夹中
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 *
>>>
Run Code Online (Sandbox Code Playgroud)
但是,当我打开一个新的shell并使用Python 2.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
>>>
Run Code Online (Sandbox Code Playgroud)
我尝试添加条目,sys.path但它没有帮助.我在这里读了一个类似的问题,但解决方案并没有帮助我,因为我尝试了相对和绝对导入.请指教.
编辑:目录结构是~/tests/libraries/controller_utils.py.我在tests目录中执行这些命令.
编辑:我已添加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
Run Code Online (Sandbox Code Playgroud)
您的libraries包丢失了该__init__.py文件.您可以使用该名称创建一个空文件,然后:
from libraries.controller_utils import *
Run Code Online (Sandbox Code Playgroud)
应该管用.
或者,如果您不想libraries变成包,则应将其路径添加到sys.path并导入controller_utils:
import sys
sys.path.append('libraries/')
from controller_utils import *
Run Code Online (Sandbox Code Playgroud)
请注意,错误是由于python2需要存在__init__.py从包导入而python3.3 +提供命名空间包(参见PEP420).这就是导入在python3.4中没有失败的原因.
如果您希望代码在python2和python3中工作方式相同,则应始终将__init__.py文件添加到包中并from __future__ import absolute_import在文件中使用.