为何首次导入失败后,后续同模块导入也失败?(正常情况不会如此)
问题原因探究:Python导入模块的异常行为差异
核心诉求
仅关注原因,不关心解决办法,需探究两段代码行为不同的诱因(该异常仅在本人电脑上出现)。
无法运行的代码示例
# demo.py伪代码(无法运行) try: from dir.file import func except: # 即使改为`except ModuleNotFoundError:`,行为也无变化 append_the_root_directory_of_this_repo_to_the_path() from dir.file import func
完整错误输出
Traceback (most recent call last): File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\bnns\scripts\demo.py", line 4, in <module> from bnns.SSGE import func ModuleNotFoundError: No module named 'bnns.SSGE' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\bnns\scripts\demo.py", line 19, in <module> from bnns.SSGE import func ModuleNotFoundError: No module named 'bnns.SSGE'
可正常运行的代码示例
# fixed_demo.py伪代码(可运行) try: 1/0 except: append_the_root_directory_of_this_repo_to_the_path() from dir.file import func
补充信息
- 代码行为依赖仓库的文件结构,需克隆对应仓库才能复现问题
- 提问者无计算机科学相关背景,希望解释尽量通俗易懂
内容的提问来源于stack exchange,提问作者Thomas Winckelman
相关产品推荐
相关产品推荐

