Skip to main content
 首页 » 编程设计

python之通过另一个函数获取函数名和文件名

2024年12月31日12Renyi-Fan

我希望 python 显示哪个函数已执行以及来自哪个文件...所以我将以下内容作为 test1.py

import sys,os, test2 
 
def some_function(): 
    print (sys._getframe().f_code.co_name +" "+ os.path.basename(__file__) , 'executed') 
    print (test2.function_details(), 'executed') 

test2.py 是:

import sys,os 
 
def function_details(): 
    return sys._getframe().f_code.co_name + " " +os.path.basename(__file__) 

现在当我运行它的时候

import test1 
 
test1.some_function() 

我得到以下输出:

('some_function test1.pyc', 'executed') 
('function_details test2.pyc', 'executed') 

当我尝试创建一个调用文件和执行函数的函数时,它告诉我我创建的子函数而不是原始函数。

我的问题是如何修改 test2.py 以便输出

('some_function test1.pyc', 'executed') 
('some_function test1.pyc', 'executed') 

请您参考如下方法:

所以 function_details 有两个问题:

  1. 当前帧是function_details,因此您需要向上一帧才能到达调用帧。为此,您将 1 传递给 sys._getframe。
  2. __file__ 是您碰巧所在的任何模块(如果已定义)的当前文件的名称,这需要替换为 co_filename 属性 f_code 与正确帧关联的对象。

纠正这两个问题,我们将 function_details 重新定义为:

def function_details(): 
    code_obj = sys._getframe(1).f_code 
    return " ".join([code_obj.co_name, os.path.basename(code_obj.co_filename)]) 

这会产生所需的结果。在我看来,inspect 模块比直接使用 sys._getframe 完成同样的事情要好得多。这是使用 inspect 编写的新 function_details:

import inspect 
def function_details(): 
    frame = inspect.getouterframes(inspect.currentframe())[1] 
    return " ".join([frame[3], os.path.basename(frame[1])])