Python不会从同一个文件夹导入模块,而是从另一个文件夹导入模块

时间:2019-09-15 11:14:56

标签: python

所以我有一个像这样的项目

root/
  api/
  nest/
    nest.py
    tests.py
    __init__.py

当我运行python nest/nest.py -args时,它工作正常,但是当我运行python nest / tests.py时,它崩溃,说我在tests.py中有导入错误。
 ModuleNotFoundError: No module named 'nest.nest'; 'nest' is not a package

我的tests.py导入看起来像这样

import unittest
from nest.nest import JsonParser

我还在api / api.py模块中使用了这个JsonParser类,它可以正常工作 除此之外,如果我在pycharm中运行tests.py,它可以正常工作,但是如果我在控制台中尝试,它将抛出此异常

1 个答案:

答案 0 :(得分:1)

问题是您的解释者在模块范围之外运行时不知道该模块所在的路径。

一个解决方案可能是在代码中添加模块的绝对路径:

import sys
sys.path.append('my/path/to/module/folder')

import module-of-interest