I’ve been searching for some useful code examples on this subject for creating a simple logger for my program.
Here are the things I’ve searched:
- Getting the current function info (name, arguments, file name and path)
- Getting the calling function into (name, file name and path, line number)
For some reason this information is scattered over many posts and locations and it would be nice to have them in one single location.
Here are all needed code examples for this purpose:
To get the file path do this:
import inspect
...
source_file_path = inspect.getfile(inspect.currentframe())
Or this:
source_file_path = __file__
Or this:
import sys
...
source_file_path = sys._getframe().f_code.co_filename
All of them return the same thing: The full path of the file in which the calling function resides:
/home/james/Documents/pythonExamples/example1.py
If you wan to get only the file name use ‘Path’ to help you:
from pathlib import Path
...
source_file_path = Path(source_file_path).name
To get the current function name do this:
import sys
...
source_func_name = sys._getframe().f_code.co_name
Or this:
import inspect
...
source_func_name = inspect.currentframe().f_code.co_name
If you’d like to also get the arguments’ list of current function do this:
import inspect
...
frame = inspect.currentframe()
argsList = inspect.getargvalues(frame).args
If you need the name of the calling function (one step back in the call-stack) – do this:
import sys
...
calling_function_name = sys._getframe().f_back.f_code.co_name
If you also want the calling function file name – do this:
calling_file_name = Path(sys._getframe().f_back.f_code.co_filename).name
And if you want the calling function line number in its file do this:
calling_function_line = sys._getframe().f_back.f_lineno
Hope this had helped.