【python & VS Code】调用自定义模块 ModuleNotFoundError: No module named XXX

写 python 很久了,今天本没打算熬夜,但却被这么简单的问题困到了 零点半 … 有点像脑筋急转弯。

在 VS Code 等轻量文本编辑器/项目管理器中,我不希望像 pycharm 一样由配置文件自动管理我们的调用模块路径。但这就有一个问题:需要我们写几行代码,将自定义模块的路径添加到系统路径中

这并不麻烦,我很喜欢微软的这个深度学习项目,我一直将其风格作为自己写 python 算法项目的规范:

其算法实现封装在 lib 中,而我们实现算法时,并不需要直接调用 lib 中的任何东西。我们只需要调用 moment_localization 中的文件。即只需要两步:

  • 训练模型:python.exe test.py
  • 测试模型:python.exe train.py

那么问题来了,test.pytrain.py 中是如何识别并调用 lib 模块的呢?

答案在 _init_paths.py 中:

import os.path as osp
import sys

def add_path(path):
    if path not in sys.path:
        sys.path.insert(0, path)

this_dir = osp.dirname(__file__)

lib_path = osp.join(this_dir, '..', 'lib')
add_path(lib_path)

简单的几行代码,获取 lib 的绝对路径,并彻底将 lib 加入我们的系统路径中。一劳永逸。甚至在 lib 中的各个模块中,也无需 init paths


那么问题来了,这么简单的道理,谁都能一看就懂,为什么很久 python 使用经验的我困在这里一个小时呢![\迷之微笑]

请记住:sys.path.append()添加的是路径不是模块!

sys.path.append()添加的是路径不是模块!

sys.path.append()添加的是路径不是模块!

在这个地方耽误时间,实在是令人汗颜:就好像善于解答压轴数学题的高中生总是计算上出现错误一样可惜。

我的文件结构是这样的:

-- library
    |-- core 
        |-- rectangle.py
    |-- utils
        |-- ...
-- test
    |-- test.py
    |-- _init_path.py

_init_path.py 中,我将 library “规范地”导入了:

import os.path as osp
import sys

def add_path(path):
    if path not in sys.path:
        sys.path.append(path)
        # print(sys.path)

this_dir = osp.dirname(__file__)

lib_path = osp.join(this_dir, '..', 'library')
add_path(lib_path)

但是当我在 test.py 中测试时,却总是告诉我:没有 library 模块

我迷惑了好久,直到我将 sys.path 打印出来:

我才终于意识到:sys.path.append()添加的是路径不是模块!

不要 import library 了!library 作为路径,已经被添加了!library 下的各个文件夹,才是我们的自定义模块,直接调用就可以了!

上午提到过,我的项目结构是:

-- library
    |-- core 
        |-- rectangle.py
    |-- utils
        |-- ...
-- test
    |-- test.py
    |-- _init_path.py

那么,直接 import core 便好。嗯。[\迷之微笑]

如果想直接通过 core 调用 rectangle.py 中的函数,可以在 core 下加一个 __init__.py

-- library
    |-- core 
        |-- rectangle.py
        |-- __init__.py
    |-- utils
        |-- ...
-- test
    |-- test.py
    |-- _init_path.py

__init__.py 在模块被调用时自动运行,其中可以有:

from .rectangle import *

.rectangle表示当前目录下的 rectangle.py 文件。


晚睡了,实在不该。

2020-3-29 00:55:31
Piper Liu

原创文章 163 获赞 177 访问量 4万+

猜你喜欢

转载自blog.csdn.net/weixin_42815609/article/details/105172127