ImportError: No module named utils

ImportError: No module named utils

我正在尝试导入实用程序文件,但仅当我通过脚本 运行 代码时才 运行 遇到奇怪的错误。

当我运行test.py

位置:/home/amourav/Python/proj/test.py

代码:

import os
os.chdir(r'/home/amourav/Python/')
print os.listdir(os.getcwd())
print os.getcwd()
from UTILS import *

输出为:

['UTILS_local.py','UTILS.py', 'proj', 'UTILS.pyc']

/home/amourav/Python

Traceback (most recent call last): File "UNET_2D_AUG17.py", line 11, in from UTILS import * ImportError: No module named UTILS

但是当我通过 bash 终端 运行 代码时,它似乎工作正常

bash-4.1$ python
>>> import os
>>> os.chdir(r'/home/amourav/Python/')
>>> print os.listdir(os.getcwd())

['UTILS_local.py','UTILS.py', 'proj', 'UTILS.pyc']

>>> from UTILS import *

blah blah -everything is fine- blah blah

我在 linux 机器上 运行ning Python 2.7.10

您的项目如下所示:

+- proj
|  +- test.py
+- UTILS.py
+- ...

如果你喜欢导入UTILS.py,你可以选择:

(1)在test.py

中添加sys.path的路径
import os, sys
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
# now you may get a problem with what I wrote below.
import UTILS

(2) 创建包(仅限导入)

Python
+- proj
|  +- test.py
|  +- __init__.py
+- UTILS.py
+- __init__.py
+- ...

现在,如果你import Python.proj.test:

,你可以在test.py中写这个
from .. import UTILS

错误答案

这个错误我有好几次了。我想,我记得。

修复:不要 运行 test.py, 运行 ./test.py.

如果你看一下sys.path,你会发现里面有一个空字符串,里面是执行文件的路径。

  • test.py'' 添加到 sys.path
  • ./test.py'.' 添加到 sys.path

我认为只能从 "." 执行导入。