自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Python探針實現(xiàn)原理

開發(fā) 后端
本文呢,將簡單講述一下 Python 探針的實現(xiàn)原理。同時為了驗證這個原理,我們也會一起來實現(xiàn)一個簡單的統(tǒng)計指定函數(shù)執(zhí)行時間的探針程序。

 

關(guān)于 Python 的導(dǎo)入機制,我以前寫過一篇文章,非常詳細(xì),感興趣的可以點擊這個鏈接進行查看:[深入探討 Python 的 import 機制:實現(xiàn)遠(yuǎn)程導(dǎo)入模塊]另外,今天再給你推薦這篇文章,同樣是介紹 Python 的導(dǎo)入機制,和上面的文章一起食用更佳。本文呢,將簡單講述一下 Python 探針的實現(xiàn)原理。同時為了驗證這個原理,我們也會一起來實現(xiàn)一個簡單的統(tǒng)計指定函數(shù)執(zhí)行時間的探針程序。探針的實現(xiàn)主要涉及以下幾個知識點:

  •  sys.meta_path
  •  sitecustomize.py

sys.meta_path

sys.meta_path 這個簡單的來說就是可以實現(xiàn) import hook 的功能, 當(dāng)執(zhí)行 import 相關(guān)的操作時,會觸發(fā) sys.meta_path 列表中定義的對象。關(guān)于 sys.meta_path 更詳細(xì)的資料請查閱 python 文檔中 sys.meta_path 相關(guān)內(nèi)容以及 PEP 0302 。

sys.meta_path 中的對象需要實現(xiàn)一個 find_module 方法, 這個 find_module 方法返回 None 或一個實現(xiàn)了 load_module 方法的對象 (代碼可以從 github 上下載 part1_) :

  1. import sysclass 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 syssys.meta_path.insert(0, MetaPathFinder())if __name__ == '__main__':    import http    print(http)    print(http.version_info) 

load_module 方法返回一個 module 對象,這個對象就是 import 的 module 對象了。比如我上面那樣就把 http 替換為 sys 這個 module 了。 

  1. $ python meta_path1.pyfind_module httpload_module http<module 'sys' (built-in)>sys.version_info(major=3minor=5micro=1releaselevel='final'serial=0

通過 sys.meta_path 我們就可以實現(xiàn) import hook 的功能:當(dāng) import 預(yù)定的 module 時,對這個 module 里的對象來個貍貓換太子, 從而實現(xiàn)獲取函數(shù)或方法的執(zhí)行時間等探測信息。上面說到了貍貓換太子,那么怎么對一個對象進行貍貓換太子的操作呢?對于函數(shù)對象,我們可以使用裝飾器的方式來替換函數(shù)對象(代碼可以從 github 上下載 part2) : 

  1. import functoolsimport timedef 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 wrapperdef sleep(n):    time.sleep(n)    return nif __name__ == '__main__':    func = func_wrapper(sleep)    print(func(3)) 

執(zhí)行結(jié)果: 

  1. $ python func_wrapper.pystart funcspent 3.004966974258423s3 

下面我們來實現(xiàn)一個計算指定模塊的指定函數(shù)的執(zhí)行時間的功能(代碼可以從 github 上下載 part3) 。假設(shè)我們的模塊文件是 hello.py: 

  1. import timedef sleep(n):    time.sleep(n)    return n 

我們的 import hook 是 hook.py: 

  1. import functoolsimport importlibimport sysimport 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`` 中保存的是已經(jīng)導(dǎo)入過的 module        if fullname in sys.modules:            return sys.modules[fullname]        # 先從 sys.meta_path 中刪除自定義的 finder        # 防止下面執(zhí)行 import_module 的時候再次觸發(fā)此 finder        # 從而出現(xiàn)遞歸調(diào)用的問題        finder = sys.meta_path.pop(0)        # 導(dǎo)入 module        module = importlib.import_module(fullname)        module_hook(fullname, module)        sys.meta_path.insert(0, finder)        return modulesys.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 

測試代碼: 

  1. >>> import hook>>> import hellofind_module helloload_module hello>>>>>> hello.sleep(3)start funcspent 3.0029919147491455s3>>> 

其實上面的代碼已經(jīng)實現(xiàn)了探針的基本功能。不過有一個問題就是上面的代碼需要顯示的 執(zhí)行 import hook 操作才會注冊上我們定義的 hook。那么有沒有辦法在啟動 python 解釋器的時候自動執(zhí)行 import hook 的操作呢?答案就是可以通過定義 sitecustomize.py 的方式來實現(xiàn)這個功能。

sitecustomize.py

簡單的說就是,python 解釋器初始化的時候會自動 import PYTHONPATH 下存在的 sitecustomize 和 usercustomize 模塊:實驗項目的目錄結(jié)構(gòu)如下(代碼可以從 github 上下載 part4) : 

  1. $ tree.├── sitecustomize.py└── usercustomize.py 

sitecustomize.py: 

  1. $ cat sitecustomize.pyprint('this is sitecustomize') 

usercustomize.py: 

  1. $ cat usercustomize.pyprint('this is usercustomize') 

把當(dāng)前目錄加到 PYTHONPATH 中,然后看看效果: 

  1. $ export PYTHONPATH=.$ pythonthis 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 darwinType "help", "copyright", "credits" or "license" for more information.>>> 

可以看到確實自動導(dǎo)入了。所以我們可以把之前的探測程序改為支持自動執(zhí)行 import hook (代碼可以從 github 上下載 part5) 。目錄結(jié)構(gòu): 

  1. $ tree.├── hello.py├── hook.py├── sitecustomize.py 

sitecustomize.py: 

  1. $ cat sitecustomize.pyimport hook 

結(jié)果: 

  1. $ export PYTHONPATH=.$ pythonfind_module usercustomizePython 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 darwinType "help", "copyright", "credits" or "license" for more information.find_module readlinefind_module atexitfind_module rlcompleter>>>>>> import hellofind_module helloload_module hello>>>>>> hello.sleep(3)start funcspent 3.005002021789551s3 

不過上面的探測程序其實還有一個問題,那就是需要手動修改 PYTHONPATH 。用過探針程序的朋友應(yīng)該會記得, 使用 newrelic 之類的探針只需要執(zhí)行一條命令就 可以了:newrelic-admin run-program python hello.py 實際上修改 PYTHONPATH 的操作是在newrelic-admin 這個程序里完成的。下面我們也要來實現(xiàn)一個類似的命令行程序,就叫 agent.py 吧。

agent

還是在上一個程序的基礎(chǔ)上修改。先調(diào)整一個目錄結(jié)構(gòu),把 hook 操作放到一個單獨的目錄下, 方便設(shè)置 PYTHONPATH 后不會有其他的干擾(代碼可以從 github 上下載 part6 )。 

  1. $ 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 的內(nèi)容修改為: 

  1. $ cat bootstrap/sitecustomize.pyimport _hook 

agent.py 的內(nèi)容如下: 

  1. import osimport syscurrent_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    # 執(zhí)行后面的 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 的內(nèi)容為: 

  1. $ cat test.pyimport sysimport helloprint(sys.argv)print(hello.sleep(3)) 

使用方法: 

  1. $ python agent.py test.py arg1 arg2find_module usercustomizefind_module helloload_module hello['test.py', 'arg1', 'arg2']start funcspent 3.005035161972046s3 

至此,我們就實現(xiàn)了一個簡單的 python 探針程序。當(dāng)然,跟實際使用的探針程序相比肯定是有 很大的差距的,這篇文章主要是講解一下探針背后的實現(xiàn)原理。 

 

責(zé)任編輯:龐桂玉 來源: 馬哥Linux運維
相關(guān)推薦

2017-05-16 15:33:42

Python網(wǎng)絡(luò)爬蟲核心技術(shù)框架

2024-08-02 11:33:49

2024-09-05 10:49:42

2020-09-10 13:51:48

Kubernetes云原生容器

2025-01-16 07:10:00

2020-09-15 08:46:26

Kubernetes探針服務(wù)端

2017-07-11 13:58:10

WebSocket

2023-12-27 06:48:49

KubernetesDevOpsHTTP

2017-07-25 16:34:06

數(shù)據(jù)庫sqlmongodb

2023-01-04 07:54:03

HashMap底層JDK

2023-01-30 18:44:45

MVCC事務(wù)

2021-02-07 09:36:20

LongAdderJDK8開發(fā)

2021-05-27 09:57:55

Inotify監(jiān)控系統(tǒng)

2014-06-06 09:01:07

DHCP

2017-12-06 16:28:48

Synchronize實現(xiàn)原理

2022-12-19 08:00:00

SpringBootWeb開發(fā)

2023-04-17 08:13:13

KubernetesPod

2021-08-26 10:30:29

WebpackTree-Shakin前端

2015-07-10 12:23:05

JsPatch實現(xiàn)原理

2015-11-12 09:39:28

微信紅包實現(xiàn)
點贊
收藏

51CTO技術(shù)棧公眾號