python的搜索路徑實際上是一個列表(sys.path)
導入模塊時python會自動去找搜索這個列表當中的路徑,若是路徑中存在要導入的模塊文件則導入成功.python
在項目中若是要引用同級包或另外目錄的包(非子包)時:git
In [1]: import sys In [2]: sys.path Out[2]: ['', '/Library/Frameworks/Python.framework/Versions/3.7/bin', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python37.zip', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/IPython/extensions',]
mac-abeen:page_pth_test abeen$ tree -L 3 ├── dakjpka │ ├── __init__.py │ ├── pa │ │ ├── __init__.py │ │ ├── __pycache__ │ │ ├── pam.py │ │ └── pam_rf.py │ └── pb │ └── pbm.py └── tpackage.py
from package import module
import packageapp
pam.py測試
1 # -*- coding: utf-8 -*- 2 3 4 def pam_fun(): 5 print('p.pa pam_fun') 6 7 8 __all__ = ['pam_fun']
pam_rf.pycode
1 # -*- coding: utf-8 -*- 2 3 from pam import pam_fun 4 5 if __name__ == "__main__": 6 pam_fun()
查看python特定目錄ip
In [3]: import site In [4]: site.getsitepackages() Out[4]: ['/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages']
增長目錄內容utf-8
mac-abeen:pa abeen$ cat /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/dakj_project.pth /Users/abeen/abeen/alearn/python/page_pth_test /Users/abeen/abeen/ap/gitwork/dabda
增長後效果get
In [5]: sys.path Out[5]: ['', '/Library/Frameworks/Python.framework/Versions/3.7/bin', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python37.zip', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages', **'/Users/abeen/abeen/alearn/python/page_pth_test',** ** '/Users/abeen/abeen/ap/gitwork/dabda',** '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/IPython/extensions', '/Users/abeen/.ipython']
pbm.py 引用pam.py內的pam_fun以下it
1 # -*- coding: utf-8 -*- 2 3 # from dakjpka.pa import pam 4 import dakjpka.pa.pam as pam 5 6 7 def pbm_fun(): 8 print('p.pbm pbm_fun') | 9 pam.pam_fun() 10 11 12 if __name__ == '__main__': 13 pbm_fun() 14 15 16 __all__ = ['pbm_fun']
runio
mac-abeen:pb abeen$ python3 pbm.py p.pbm pbm_fun p.pa pam_fun