打印调用该函数的文件的文件名的函数

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

我想创建一个日志函数,记录调用日志函数的文件的名称,后跟我要记录的消息 'message'

functions.py

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

main.py

log('message')

这个returns:

functions.py: message

我想要 return:

main.py: message

您可以首先使用 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 模块通过解释器的堆栈返回。

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