多人學習python,不知道從何學起,
很多人學習python,掌握了基本語法過后,不知道在哪里尋找案例上手,
很多已經做案例的人,卻不知道如何去學習更加高深的知識,
那么針對這三類人,我給大家提供一個好的學習平臺,免費領取視頻教程,電子書籍,以及課程的源代碼!??¤
QQ群:1057034340
One old watch, like brief python

原文:
關于 Python 的匯入機制,我以前寫過一篇文章,非常詳細,感興趣的可以點擊這個鏈接進行查看: 深入探討 Python 的 import 機制:實作遠程匯入模塊
另外,今天再給你推薦這篇文章,同樣是介紹 Python 的匯入機制,和上面的文章一起食用更佳,
本文呢,將簡單講述一下 Python 探針的實作原理,同時為了驗證這個原理,我們也會一起來實作一個簡單的統計指定函式執行時間的探針程式,
探針的實作主要涉及以下幾個知識點:
-
sys.meta_path
-
sitecustomize.py
sys.meta_path
sys.meta_path 這個簡單的來說就是可以實作 import hook 的功能, 當執行 import 相關的操作時,會觸發 sys.meta_path 串列中定義的物件,關于 sys.meta_path 更詳細的資料請查閱 python 檔案中 sys.meta_path 相關內容以及 PEP 0302 ,
sys.meta_path 中的物件需要實作一個 find_module 方法, 這個 find_module 方法回傳 None或一個實作了 load_module 方法的物件 (代碼可以從 github 上下載 part1_) :
import sys
class MetaPathFinder:
def find_module(self, fullname, path=None):
print('find_module {}'.format(fullname))
return MetaPathLoader()
class MetaPathLoader:
def load_module(self, fullname):
print('load_module {}'.format(fullname))
sys.modules[fullname] = sys
return sys
sys.meta_path.insert(0, MetaPathFinder())
if __name__ == '__main__':
import http
print(http)
print(http.version_info)
load_module 方法回傳一個 module 物件,這個物件就是 import 的 module 物件了,比如我上面那樣就把 http 替換為 sys 這個 module 了,
$ python meta_path1.py
find_module http
load_module http
<module 'sys' (built-in)>
sys.version_info(major=3, minor=5, micro=1, releaselevel='final', serial=0)
通過 sys.meta_path 我們就可以實作 import hook 的功能:當 import 預定的 module 時,對這個 module 里的物件來個貍貓換太子, 從而實作獲取函式或方法的執行時間等探測資訊,
上面說到了貍貓換太子,那么怎么對一個物件進行貍貓換太子的操作呢?對于函式物件,我們可以使用裝飾器的方式來替換函式物件(代碼可以從 github 上下載 part2) :
import functools
import time
def func_wrapper(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print('start func')
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print('spent {}s'.format(end - start))
return result
return wrapper
def sleep(n):
time.sleep(n)
return n
if __name__ == '__main__':
func = func_wrapper(sleep)
print(func(3))
執行結果:
$ python func_wrapper.py
start func
spent 3.004966974258423s
3
下面我們來實作一個計算指定模塊的指定函式的執行時間的功能(代碼可以從 github 上下載 part3) ,
假設我們的模塊檔案是 hello.py:
import time
def sleep(n):
time.sleep(n)
return n
我們的 import hook 是 hook.py:
import functools
import importlib
import sys
import time
_hook_modules = {'hello'}
class MetaPathFinder:
def find_module(self, fullname, path=None):
print('find_module {}'.format(fullname))
if fullname in _hook_modules:
return MetaPathLoader()
class MetaPathLoader:
def load_module(self, fullname):
print('load_module {}'.format(fullname))
# ``sys.modules`` 中保存的是已經匯入過的 module
if fullname in sys.modules:
return sys.modules[fullname]
# 先從 sys.meta_path 中洗掉自定義的 finder
# 防止下面執行 import_module 的時候再次觸發此 finder
# 從而出現遞回呼叫的問題
finder = sys.meta_path.pop(0)
# 匯入 module
module = importlib.import_module(fullname)
module_hook(fullname, module)
sys.meta_path.insert(0, finder)
return module
sys.meta_path.insert(0, MetaPathFinder())
def module_hook(fullname, module):
if fullname == 'hello':
module.sleep = func_wrapper(module.sleep)
def func_wrapper(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print('start func')
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print('spent {}s'.format(end - start))
return result
return wrapper
測驗代碼:
>>> import hook
>>> import hello
find_module hello
load_module hello
>>>
>>> hello.sleep(3)
start func
spent 3.0029919147491455s
3
>>>
其實上面的代碼已經實作了探針的基本功能,不過有一個問題就是上面的代碼需要顯示的 執行 import hook 操作才會注冊上我們定義的 hook,
那么有沒有辦法在啟動 python 解釋器的時候自動執行 import hook 的操作呢?答案就是可以通過定義 sitecustomize.py 的方式來實作這個功能,
sitecustomize.py
簡單的說就是,python 解釋器初始化的時候會自動 import PYTHONPATH 下存在的 sitecustomize 和 usercustomize 模塊:
實驗專案的目錄結構如下(代碼可以從 github 上下載 part4) :
$ tree
.
├── sitecustomize.py
└── usercustomize.py
sitecustomize.py:
$ cat sitecustomize.py
print('this is sitecustomize')
usercustomize.py:
$ cat usercustomize.py
print('this is usercustomize')
把當前目錄加到 PYTHONPATH 中,然后看看效果:
$ export PYTHONPATH=.
$ python
this is sitecustomize <----
this is usercustomize <----
Python 3.5.1 (default, Dec 24 2015, 17:20:27)
[GCC 4.2.1 Compatible Apple LLVM 7.0.2 (clang-700.1.81)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
可以看到確實自動匯入了,所以我們可以把之前的探測程式改為支持自動執行 import hook (代碼可以從 github 上下載 part5) ,
目錄結構:
$ tree
.
├── hello.py
├── hook.py
├── sitecustomize.py
sitecustomize.py:
$ cat sitecustomize.py
import hook
結果:
$ export PYTHONPATH=.
$ python
find_module usercustomize
Python 3.5.1 (default, Dec 24 2015, 17:20:27)
[GCC 4.2.1 Compatible Apple LLVM 7.0.2 (clang-700.1.81)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
find_module readline
find_module atexit
find_module rlcompleter
>>>
>>> import hello
find_module hello
load_module hello
>>>
>>> hello.sleep(3)
start func
spent 3.005002021789551s
3
不過上面的探測程式其實還有一個問題,那就是需要手動修改 PYTHONPATH ,用過探針程式的朋友應該會記得, 使用 newrelic 之類的探針只需要執行一條命令就 可以了: newrelic-admin run-program python hello.py 實際上修改 PYTHONPATH 的操作是在 newrelic-admin 這個程式里完成的,
下面我們也要來實作一個類似的命令列程式,就叫 agent.py 吧,
agent
還是在上一個程式的基礎上修改,先調整一個目錄結構,把 hook 操作放到一個單獨的目錄下, 方便設定 PYTHONPATH 后不會有其他的干擾(代碼可以從 github 上下載 part6 ),
$ mkdir bootstrap
$ mv hook.py bootstrap/_hook.py
$ touch bootstrap/__init__.py
$ touch agent.py
$ tree
.
├── bootstrap
│ ├── __init__.py
│ ├── _hook.py
│ └── sitecustomize.py
├── hello.py
├── test.py
├── agent.py
bootstrap/sitecustomize.py 的內容修改為:
$ cat bootstrap/sitecustomize.py
import _hook
agent.py 的內容如下:
import os
import sys
current_dir = os.path.dirname(os.path.realpath(__file__))
boot_dir = os.path.join(current_dir, 'bootstrap')
def main():
args = sys.argv[1:]
os.environ['PYTHONPATH'] = boot_dir
# 執行后面的 python 程式命令
# sys.executable 是 python 解釋器程式的絕對路徑 ``which python``
# >>> sys.executable
# '/usr/local/var/pyenv/versions/3.5.1/bin/python3.5'
os.execl(sys.executable, sys.executable, *args)
if __name__ == '__main__':
main()
test.py 的內容為:
$ cat test.py
import sys
import hello
print(sys.argv)
print(hello.sleep(3))
使用方法:
$ python agent.py test.py arg1 arg2
find_module usercustomize
find_module hello
load_module hello
['test.py', 'arg1', 'arg2']
start func
spent 3.005035161972046s
3
至此,我們就實作了一個簡單的 python 探針程式,當然,跟實際使用的探針程式相比肯定是有 很大的差距的,這篇文章主要是講解一下探針背后的實作原理,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/222673.html
標籤:Python
上一篇:Java基礎
下一篇:用Python解“智力游戲”
