如何解决在命令行运行Python时出现的ModuleNotFoundError错误?

2026-05-17 00:251阅读0评论SEO资源
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计414个文字,预计阅读时间需要2分钟。

如何解决在命令行运行Python时出现的ModuleNotFoundError错误?

python运行py文件时,确保文件位于子目录中,并且该文件引用了另一个子目录中的py模块。类似情况:因环境原因,a.py找不到b.py,抛出ModuleNotFoundError。解决方法:将父文件夹的路径添加到sys.path中。

所要运行的 py 文件在子目录中,并且该文件引用了另一个子目录中的 py 模块。类似这样:

原因

在运行环境下, a.py 找不到 b.py 所以抛出 ModuleNotFoundError。

解决

把父文件夹的所在路径加入运行环境,代码如下:

import os import sys dirname = os.path.dirname(__file__) curPath = os.path.abspath(dirname) r= os.path.split(curPath) rootPath = r[0] sys.path.append(rootPath)

os.path.dirname(__file__) 会返回当前文件的目录名称,包含路径。

如何解决在命令行运行Python时出现的ModuleNotFoundError错误?

os.path.abspath(dirname) 返回标准化后的当前文件所在目录的绝对路径。

os.path.split(path) 会将路径 path 拆分为一对,即 (head, tail),其中,tail 是路径的最后一部分,而 head 里是除最后部分外的所有内容。tail 部分不会包含斜杠,如果 path 以斜杠结尾,则 tail 将为空。如果 path 中没有斜杠,head 将为空。如果 path 为空,则 head 和 tail 均为空。所以对其结果取第 0 位的值,就是 head。

sys.path.append(rootPath) 把 rootPath 加入运行环境。


参考:
docs.python.org/zh-cn/3.7/
www.cnblogs.com/gylhaut/p/9889917.html

本文共计414个文字,预计阅读时间需要2分钟。

如何解决在命令行运行Python时出现的ModuleNotFoundError错误?

python运行py文件时,确保文件位于子目录中,并且该文件引用了另一个子目录中的py模块。类似情况:因环境原因,a.py找不到b.py,抛出ModuleNotFoundError。解决方法:将父文件夹的路径添加到sys.path中。

所要运行的 py 文件在子目录中,并且该文件引用了另一个子目录中的 py 模块。类似这样:

原因

在运行环境下, a.py 找不到 b.py 所以抛出 ModuleNotFoundError。

解决

把父文件夹的所在路径加入运行环境,代码如下:

import os import sys dirname = os.path.dirname(__file__) curPath = os.path.abspath(dirname) r= os.path.split(curPath) rootPath = r[0] sys.path.append(rootPath)

os.path.dirname(__file__) 会返回当前文件的目录名称,包含路径。

如何解决在命令行运行Python时出现的ModuleNotFoundError错误?

os.path.abspath(dirname) 返回标准化后的当前文件所在目录的绝对路径。

os.path.split(path) 会将路径 path 拆分为一对,即 (head, tail),其中,tail 是路径的最后一部分,而 head 里是除最后部分外的所有内容。tail 部分不会包含斜杠,如果 path 以斜杠结尾,则 tail 将为空。如果 path 中没有斜杠,head 将为空。如果 path 为空,则 head 和 tail 均为空。所以对其结果取第 0 位的值,就是 head。

sys.path.append(rootPath) 把 rootPath 加入运行环境。


参考:
docs.python.org/zh-cn/3.7/
www.cnblogs.com/gylhaut/p/9889917.html