import導入模塊
cli的目錄結構如下
? cli tree
.
├── __pycache__
│ └── test.cpython-36.pyc
├── demo1
├── demo2
│ ├── __pycache__
│ │ └── test2.cpython-36.pyc
│ └── test2.py
└── test.py
若直接在test.py中import test2
則會報以下錯誤
? cli python3
Python 3.6.0 (default, Jan 23 2017, 14:53:49)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import test2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'test2'
通過以下方式查看import的搜索路徑
>>> import sys
>>> sys.path
[
'',
'/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/lib/python36.zip',
'/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/lib/python3.6',
'/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3
]
所以可以將test2.Py的路徑加入上面的目錄的方式來解決
>>> sys.path
[
'',
'/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/lib/python36.zip',
'/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/lib/python3.6',
'/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3,
'./demo2/'
]
// 重新導入后沒有再報錯
>>> import test2
>>>
>>>
由于此時的test2.py文件內(nèi)容為空
另開一個窗口編輯test2.py ,增加一個hello方法
15148114276369.jpg
回到左側調(diào)用hello方法會報以下錯誤
>>> import test2
>>> test2.hello()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'test2' has no attribute 'hello'
當然可以通過推出在重新導入的方式是可以的,另一種方式就是該篇的第二個話題:動態(tài)加載
動態(tài)加載模塊
場景:開了2個窗口同時編輯同一個文件,但又不想退出重進
>>> from imp import *
>>> reload(test2)
<module 'test2' from './demo2/test2.py'>
此時在調(diào)用hello方法即可
>>> test2.hello()
hello