Python 导入错误:没有名为 utils 的模块
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45741254/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ImportError: No module named utils
提问by A.Mouraviev
I'm trying to import a utilities file but running into a weird error only when I run the code through a script.
我正在尝试导入实用程序文件,但仅当我通过脚本运行代码时才遇到奇怪的错误。
When I run test.py
当我运行 test.py
location: /home/amourav/Python/proj/test.py
位置:/home/amourav/Python/proj/test.py
code:
代码:
import os
os.chdir(r'/home/amourav/Python/')
print os.listdir(os.getcwd())
print os.getcwd()
from UTILS import *
The output is:
输出是:
['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
['UTILS_local.py','UTILS.py','proj','UTILS.pyc']
/家/amourav/Python
回溯(最近一次调用):文件“UNET_2D_AUG17.py”,第 11 行,从 UTILS 导入 * 导入错误:没有名为 UTILS 的模块
but when I run the code through the bash terminal, it seems to work fine
但是当我通过 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']
['UTILS_local.py','UTILS.py','proj','UTILS.pyc']
>>> from UTILS import *
blah blah -everything is fine- blah blah
等等等等 - 一切都很好 - 等等
I'm running Python 2.7.10 on a linux machine
我在 Linux 机器上运行 Python 2.7.10
采纳答案by User
Your project looks like this:
您的项目如下所示:
+- proj
| +- test.py
+- UTILS.py
+- ...
If you like to import UTILS.py, you can choose:
如果你喜欢导入UTILS.py,你可以选择:
(1) add the path to sys.path in test.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) create a package (imports only)
(2) 创建一个包(仅限导入)
Python
+- proj
| +- test.py
| +- __init__.py
+- UTILS.py
+- __init__.py
+- ...
Now, you can write this in test.py if you import Python.proj.test
:
现在,你可以在 test.py 中写这个,如果你import Python.proj.test
:
from .. import UTILS
WRONG ANSWER
错误的答案
I had this error several times. I think, I remember.
我多次遇到此错误。我想,我记得。
Fix: do not run test.py
, run ./test.py
.
修复:不运行test.py
,运行./test.py
。
If you have a look at sys.path
, you can see that there is an empty string inside which is the path of the file executed.
如果你看看sys.path
,你可以看到里面有一个空字符串,它是执行文件的路径。
test.py
adds''
tosys.path
./test.py
adds'.'
tosys.path
test.py
添加''
到sys.path
./test.py
添加'.'
到sys.path
Imports can only be performed from "."
, I think.
"."
我认为只能从 执行导入。