jason
jason

Reputation: 4439

Getting function name and file name through another function

I want python to show me which function has been executed and from what file... so I have the following as 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 is:

import sys,os

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

now when I run it

import test1

test1.some_function()

I get the following output:

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

When I try to make a function for calling the file and function of the executed, it tells me the sub function I made instead of the original.

My question is how do I modify test2.py so it will output

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

Upvotes: 2

Views: 888

Answers (1)

Matthew Story
Matthew Story

Reputation: 3783

So there are two issues with function_details:

  1. The current frame is function_details so you need to go up one frame to get to the calling frame. To do this you pass 1 to sys._getframe.
  2. __file__ is the name of the current file for whatever module you happen to be in (if defined), this needs to be replaced with the co_filename attribute of the f_code object associated with the correct frame.

Correcting both of these things, we redefine function_details as:

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

Which produces the desired result. In my opinion, the inspect module accomplishes this same thing far better than using sys._getframe directly. Here's the new function_details written using inspect:

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

Upvotes: 3

Related Questions