python导入的目录查找规则,如下报错是什么原因?

新手上路,请多包涵

请问python导入的目录查找规则是什么,为什么会有如下现象

test1中,import test2 --正常;
test1中,from directory1 import test2 --正常;
test1中,from directory1.directory2 import test4 --正常;
test3中,import test2 --异常:No module named test4
test3中,from directory2 import test5 --异常:Unresolved reference 'directory' 

目录结构如下,工程内有test1.py、tes2.py、directory1文件夹;
directory1文件夹下有test3.py、tes4.py、directory2文件夹;
directory2文件夹下有test5.py文件

--test1.py
--test2.py
--directory1--test3.py
--test4.py
--directory2--test5.py

阅读 1.9k
2 个回答

python 中导包有以下两种情况:

  • python 中导入包默认以当前执行脚本所在目录作为首选搜索项,可以向下检索,即 test1.py 中可以通过 import directory1.test3 来导入下级的包。
  • 当需要从 test3.py 中导入 test2.py 时(上级目录或其他目录),则需要先将 test2.py 所在的目录路径加入到 sys.path 中才可以导入。

    程序启动时将初始化本列表,列表的第一项 path[0] 目录含有调用 Python 解释器的脚本。如果脚本目录不可用(比如以交互方式调用了解释器,或脚本是从标准输入中读取的),则 path[0] 为空字符串,这将导致 Python 优先搜索当前目录中的模块。注意,脚本目录将插入在 PYTHONPATH 的条目之前。

另外推荐看一看官方文档 import 语句导入系统sys.path

python 导入包时,是按 sys.path 里面的路径为根搜索的,默认是包含当前目录的,当前目录的子目录不包含。如果在非根下的包要导入同级包,用语法 from . import xxxx

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题