gpt4 book ai didi

python - 导入错误 : No module named utils

转载 作者:太空狗 更新时间:2023-10-29 18:07:32 26 4
gpt4 key购买 nike

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

当我运行 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 机器上运行 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

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

关于python - 导入错误 : No module named utils,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45741254/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com