python导入py文件模块


有时我们写了一些lib文件,想作为模块导入引用

python import导入模块时搜索模块文件路径在 sys.path

在root下执行的 t.py (print sys.path)

['/root', '/usr/lib64/python27.zip', '/usr/lib64/python2.7', '/usr/lib64/python2.7/plat-linux2', '/usr/lib64/python2.7/lib-tk', '/usr/lib64/python2.7/lib-old', '/usr/lib64/python2.7/lib-dynload', '/usr/lib64/python2.7/site-packages', '/usr/lib/python2.7/site-packages']

 

默认会在执行脚本的当前路径下去找,找不到时回去python 的lib目录等依次去找

有时需要手动将某个文件的路径加入到 sys.path中

 模块路径中加入项目代码主目录

下面的代码是cloud-init 部分中的源码,将项目root目录插入到 sys.path中,用来导入项目目录下的模块文件

sys.path.insert(0, find_root())
sys.path.append(find_root())

 

有时可以使用imp 模块 来导入一个绝对路径的文件

[root@test ~]# cat /home/file.py
def printinfo():
    print("hello world")

#test.py
import imp

testfunc = imp.load_source('testfunc', '/home/file.py')
testfunc.printinfo()
#打印hello world

imp.load_source('testfunc', '/home/file.py')  中的 testfunc 为导入模块的名字,这里经过测试可以随便写


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM