首页 > 解决方案 > 使用符号链接时出现 ModuleNotFoundError

问题描述

我有以下目录结构

parent_directory/
+-- utils.py
+-- child_directory/
|   +-- script.py
+-- results_directory/
|   +-- results1
|   +-- results2

有几个脚本child_directory/不会相互导入任何内容。然而,他们utils.pyparent_directory/results_directory. 而不是将脚本一一复制到父目录。我只想child_directory/script.pyparent_directory. 从内部parent_directory我使用ln -s child_directory/script.py .or建立链接ln -s absolute/path/to/child_directory/script.py .。然后python script.py用来运行脚本。

下面是一个示例代码script.py

from utils.py import results_reader

# Do work

当我使用符号链接运行脚本时,parent_directory出现以下错误:

ModuleNotFoundError: No module named 'utils'

我不太明白这里发生了什么。os.getcwd()显示当前路径为parent_directory/. 它不应该能够读取utils.py文件吗?当我script.py通过将其复制到parent_directory/它运行时运行没有错误

当我更改from utils.py import results_reader为时from .utils.py import results_reader,我收到以下错误:

ModuleNotFoundError: No module named '__main__.utils'; '__main__' is not a package

标签: pythonpython-3.xpython-3.6

解决方案


推荐阅读