简体   繁体   English

获取导入文件的__file__

[英]Get __file__ of the IMPORTING file

Say there is a file tree of: 说有一个文件树:

sample_module
  |___ file1.py
  |___ file2.py

How can I get file2 's __file__ , from a function in file1 ? 如何从file1的函数获取file2__file__

file1.py : 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

How can I make it give me C:/.../file2.py ? 如何使它给我C:/.../file2.py

I understand that the function get_file_path is saving the __file__ into its namespace, and is not generating a new __file__ . 我知道get_file_path函数get_file_path __file__保存到其命名空间中,并且不会生成新的__file__ Is there a way to make __file__ callable, or get the __file__ at runtime? 有没有办法使__file__可调用,或在运行时获取__file__


Why I need it? 我为什么需要它?

I have a library, with a logging module, that generates a logger. 我有一个带有日志记录模块的库,可以生成记录器。

I want the location of that logger to be eg 2 folders above file importing generate_logger . 我希望该记录器的位置例如是文件import generate_logger上方的2个文件夹。 I'd rather not the user have to specify __file__ each time they want to use it. 我希望用户每次使用__file__都不必指定它。 Is there a better way? 有没有更好的办法?

ie in mylibrary/logs.py 即在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).       

in loads_generate_logger loads_generate_logger

 from mylibrary import generate_logger()
 logger = generate_logger()
 # logger path = C:/.../venv/lib/site-packages/mylib-0.10/logs

you can try this: 您可以尝试以下方法:

import inspect

current_frame = inspect.currentframe()

current_frame.f_back.f_globals['__file__']

this will get the __file__ global from the function that called your function 这将从调用您的函数的函数中获取__file__全局变量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM