获取调用函数的文件的绝对路径?

And*_*ius 5 python path python-3.x

t1如果file 中有方法a.py并且有一个 file ,则从文件中b.py调用方法。如何获取方法内文件的完整/绝对路径?t1a.pyb.pyt1

使用检查模块(就像这里:how to get the caller's filename, method name in python),我可以获取文件的相对路径,但它似乎不包含绝对路径(或者还有一些其他属性对象,可以访问得到它?)。

举个例子:

a.py:

def t1():
    print('callers absolute path')
Run Code Online (Sandbox Code Playgroud)

b.py:

from a import t1
t1()  # should print absolute path for `b.py`
Run Code Online (Sandbox Code Playgroud)

And*_*ius 5

import os
import inspect


def get_cfp(real: bool = False) -> str:
    """Return caller's current file path.

    Args:
        real: if True, returns full path, otherwise relative path
            (default: {False})
    """
    frame = inspect.stack()[1]
    p = frame[0].f_code.co_filename
    if real:
        return os.path.realpath(p)
    return p
Run Code Online (Sandbox Code Playgroud)

从另一个模块运行:

from module import my_module
p1 = my_module.get_cfp()
p2 = my_module.get_cfp(real=True)
print(p1)
print(p2)
Run Code Online (Sandbox Code Playgroud)

印刷:

test_path/my_module_2.py
/home/user/python-programs/test_path/my_module_2.py
Run Code Online (Sandbox Code Playgroud)


小智 0

你可以通过ospython中的模块来获取它。

>>> import a
>>> os.path.abspath(a.__file__)
Run Code Online (Sandbox Code Playgroud)