Home > OS >  Function to print the file name of the file that is calling the function
Function to print the file name of the file that is calling the function

Time:04-17

I want to create a log function that logs the name of the file that is calling the log function followed by the message I want to log 'message'

functions.py

def log(text):
    print(os.path.basename(__file__) ": " text)

main.py

log('message')

this returns:

functions.py: message

I want it to return:

main.py: message

CodePudding user response:

You can do it by first reaching back through the interpreter's stack using the inspect module and retrieving the name of the path to caller's file, and then extracting the file's name from that (which is very easy using the pathlib module).

main.py:

from functions import log

log('message')

functions.py:

import inspect
from pathlib import Path

def log(text):
    caller_path = Path(inspect.stack()[1][1])
    print(f'{caller_path.name}: {text}')
  • Related