背景:
最近用jenkins跑python自动化时,出现了模块之间引入总是类似下面的错误,所以总结了一下常见的模块导入场景
ModuleNotFoundError: No module named 'utils'
情形一、两个py文件在同一个目录,例如,在d1中导入d2的方法,直接使用from xx import xx 导入即可
#d1.py
from d2 import hello
hello()
#d2.py
def hello():
print("i am d2")
执行`python d/d1.py`后,输出结果:
PS G:\test-python> python d/d1.py
i am d2
情形二:两个文件分别在两个目录,在e.py中导入f1的方法,需要使用sys模块加上path路径,一层目录加上一层相对路径../,如果多层,则多加上对应的../
#e.py
import sys
import os
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__),"../")))
from f.f1 import hello
hello()
#f1.py
def hello():
print("i am f")
运行e.py后的结果
PS G:\test-python> python e/e.py
i am f
情形三:在情形二的基础上,加上f2.py,并且f1.py中需要导入f2.py的方法,需要注意的是,f1导入f2时,必须使用.f2格式,否则提示找不到模块
#e.py
import sys
import os
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__),"../")))
from f.f1 import test
test()
#f1.py
from .f2 import hello
def test():
print("i am f1,and import {}".format(hello()))
#f2.py
def hello():
return "f2"
运行脚本结果
PS G:\test-python> python e/e.py
i am f1,and import f2
其他复杂情况可以类似衍生