打日志的時候,經常會需要遇到打印當前函數名,以及執行他的函數名稱。如果打印的函數名稱正確的話,查詢定位問題的原因效率就會提升,如果沒有,查找代碼就會麻煩的很。
這里介紹幾個方法:sys模塊,inspect模塊
1、獲取函數名稱,獲取類名稱。
## 獲取函數名稱 def test_func(): pass print('函數名稱為:',test_func.__name__) ##獲取類名稱 class Test: def test(self): print(self.__class__.__name__) print('類名稱為:',Test().__class__.__name__) t = Test().test()
結果為:
函數名稱為: test_func 類名稱為: Test Test
2、在函數內部或者類內部獲取函數名稱,可以使用sys模塊中的sys._getframe().f_code.co_name,如下例:
import sys ## 函數獲取函數名稱 def test_sys(): print('當前函數名稱:',sys._getframe().f_code.co_name) test_sys() ##類獲取函數名稱 class TestSys: def ts(self): print('當前函數名稱:', sys._getframe().f_code.co_name) t = TestSys() t.ts()
結果:
當前函數名稱: test_sys 當前函數名稱: ts
當然,一般常用的是在不同的函數里調用的他,想要打印調用他的函數,我們嘗試一下
import sys ## 函數獲取函數名稱 def a(): print('當前函數名稱:',sys._getframe().f_code.co_name) def use_a(): ## 使用a函數 a() ## 調用使用a函數 print('------函數調用------') use_a() ##類獲取函數名稱 class TestSys: def testa(self): print('當前函數名稱:', sys._getframe().f_code.co_name) def testb(self): self.testa() ## 一個類時 print('------單個類時內部調用------') t = TestSys() t.testb() class Testsys: def testc(self): TestSys().testa() ## 兩個類時,第二個類調用第一個類 print('------多個類時內部調用------') t = Testsys() t.testc()
結果為:
------函數調用------ 當前函數名稱: a ------單個類時內部調用------ 當前函數名稱: testa ------多個類時內部調用------ 當前函數名稱: testa
由上可見,sys.__getframe().f_code.co_name是只能打印自己所在函數的名稱,無法打印調用他的函數名稱
3、使用inspect模塊中的inspect.stack()方法,動態獲取當前運行的函數名(或方法名稱),我們看一個例子
import inspect ## 函數獲取函數名稱 def a(): print('當前函數名稱:',inspect.stack()[1][3])def use_a(): ## 使用a函數 a() ## 調用使用a函數 print('------函數調用------') use_a() ##類獲取函數名稱 class TestSys: def testa(self): print('當前函數名稱:', inspect.stack()[1][3]) def testb(self): self.testa() ## 一個類時 print('------單個類時內部調用------') t = TestSys() t.testb() class Testsys: def testc(self): TestSys().testa() ## 兩個類時,第二個類調用第一個類 print('------多個類時內部調用------') t = Testsys() t.testc()
結果為:
------函數調用------ 當前函數名稱: use_a ------單個類時內部調用------ 當前函數名稱: testb ------多個類時內部調用------ 當前函數名稱: testc
由上可見,inspect.stack()打印的是調用他的函數
有了這幾種方法的支持,可以隨心所欲的打log了,可以明晰的打印出那個函數的名稱