'Get in a python function the name of the caller function file [duplicate]
This code will print a message followed by m1.py, that's the file name obtained from calling os.path.basename. Instead, I need the log function to get the file name of the caller, in this case m2.py (that's the file that generates the log entry 'message'). How to achieve that?
m1.py
def log(message):
print(message + ' ' + os.path.basename(__file__))
m2.py
from m1 import log
def func():
log('some message')
func()
Solution 1:[1]
use inspect module :
import inspect
def log(message):
frm = inspect.stack()[1].filename
print('[%s] %s' % (frm, message))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
