python中的utils模块_ImportError:没有名为utils的模块

1586010002-jmsa.png

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

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']

/home/amourav/Python

Traceback (most recent call last):

File "UNET_2D_AUG17.py", line 11, in

from UTILS import *

ImportError: No module named UTILS

but when I run the code through the bash terminal, it seems to work fine

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

I'm running Python 2.7.10 on a linux machine

解决方案

Your project looks like this:

+- proj

| +- test.py

+- UTILS.py

+- ...

If you like to import UTILS.py, you can choose:

(1) add the path to sys.path in test.py

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)

Python

+- proj

| +- test.py

| +- __init__.py

+- UTILS.py

+- __init__.py

+- ...

Now, you can write this in test.py if you 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.

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.

test.py adds '' to sys.path

./test.py adds '.' to sys.path

Imports can only be performed from ".", I think.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值