Python3 - import導入模塊,編輯的過程中動態(tài)加載模塊

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
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 134,915評論 18 139
  • 經(jīng)常在運行一些Python項目的時候會出現(xiàn)模板報錯的情況,比如以下的報錯信息: 出現(xiàn)這種情況,可能會是沒有安裝某個...
    CC先生之簡書閱讀 6,880評論 0 1
  • 用 python 解釋器來編程從 Python 解釋器退出再進入,那么你定義的所有的方法和變量就都消失了。 為此...
    chen_000閱讀 541評論 0 3
  • 22年12月更新:個人網(wǎng)站關停,如果仍舊對舊教程有興趣參考 Github 的markdown內(nèi)容[https://...
    tangyefei閱讀 35,224評論 22 257
  • 被蕭瑟帶進房間后,所有人都各回各屋了,蕭瑟說,他們閣主明日就游玩回來了,也不知道他們閣主是什么樣的人…… 在床上幻...
    蒲普閱讀 2,687評論 0 2