[英]ImportError: No module named utils
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 location:/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']
['UTILS_local.py','UTILS.py','proj','UTILS.pyc']
/home/amourav/Python
/家庭/ amourav / Python的
Traceback (most recent call last): File "UNET_2D_AUG17.py", line 11, in from UTILS import * ImportError: No module named UTILS
回溯(最近一次调用最后一次):文件“UNET_2D_AUG17.py”,第11行,来自UTILS import * ImportError:没有名为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
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
: 现在,如果
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 ''
to sys.path
test.py
将''
添加到sys.path
./test.py
adds '.'
./test.py
添加'.'
to sys.path
sys.path
Imports can only be performed from "."
导入只能从
"."
执行"."
, I think. , 我认为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.