0blex
0blex

Reputation: 13

Function to print the file name of the file that is calling the function

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

Upvotes: 1

Views: 1808

Answers (1)

martineau
martineau

Reputation: 123423

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}')

Upvotes: 2

Related Questions