编程语言
首页 > 编程语言> > 在命令行运行 python 抛出 ModuleNotFoundError 的解决方法

在命令行运行 python 抛出 ModuleNotFoundError 的解决方法

作者:互联网

所要运行的 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__) 会返回当前文件的目录名称,包含路径。

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 加入运行环境。


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

标签:__,head,python,tail,命令行,path,ModuleNotFoundError,dirname,os
来源: https://www.cnblogs.com/deniro/p/16030856.html