获取导入文件的__file__

时间:2018-07-11 09:14:15

标签: python

说有一个文件树:

sample_module
  |___ file1.py
  |___ file2.py

如何从file2中的函数中获取__file__的{​​{1}}?

file1

file1.py

def get_file_path(): return __file__

file2.py

如何使它给我from sample_module.file1 import get_file_path print(get_file_path()) # C:/.../sample_module/file1.py

我知道函数C:/.../file2.py正在将get_file_path保存到其命名空间中,并且没有生成新的__file__。有没有办法使__file__可以调用,或者在运行时获取__file__


我为什么需要它?

我有一个带有日志记录模块的库,可以生成记录器。

我希望该记录器的位置为导入__file__的文件上方有2个文件夹。 我希望用户每次使用generate_logger时都不必指定它。 有更好的方法吗?

即在__file__

mylibrary/logs.py

-

def generate_logger(logname=__name__, level=logging.DEBUG, path=''):
    """Creates a logger instance. Set level of file handler.
    """
    logger = logging.getLogger(logname)
    if path == '':
        path = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../logs'))
    fh = logging.FileHandler(f'{path}/{logname}.log')
    ## rest of logging code.
    return logger

project |___ project | |__ log | |__ loads_generate_logger (code that does the import) |_______logs |_logname.log (creates a log folder 2 folders above where it was imported).

loads_generate_logger

1 个答案:

答案 0 :(得分:0)

您可以尝试以下操作:

import inspect

current_frame = inspect.currentframe()

current_frame.f_back.f_globals['__file__']

这将从调用您函数的函数中获取__file__全局变量