1

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()
ps0604
  • 1,227
  • 23
  • 133
  • 330

1 Answers1

1

use inspect module :

import  inspect


def log(message):
    frm = inspect.stack()[1].filename
    print('[%s] %s' % (frm, message))
eshirvana
  • 23,227
  • 3
  • 22
  • 38