有時我們寫了一些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 為導入模塊的名字,這里經過測試可以隨便寫