繁体   English   中英

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

[英]Python doesnt import module from the same folder it imports another

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

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,它可以正常工作,但是如果我在控制台中尝试,它将抛出此异常

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

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

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

import module-of-interest

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM