如何在python中获取调用者的文件名,方法名称

Zhe*_* Li 19 python

例如,a.boo方法调用b.foo方法.在b.foo方法中,我如何获取文件名(我不想传递__file__b.foo方法)...

Thi*_*ter 31

您可以使用该inspect模块来实现此目的:

frame = inspect.stack()[1]
module = inspect.getmodule(frame[0])
filename = module.__file__
Run Code Online (Sandbox Code Playgroud)

  • `inspect.getmodule()` 在某些情况下可能会返回 `None`,所以更安全的方法是: ```filename = frame[0].f_code.co_filename``` (5认同)
  • 为什么不只是`filename = frame[1]`(或python 3.5+中的`frame.filename`)? (3认同)

win*_*rrr 17

蟒蛇 3.5+

单线

要获取完整的文件名(带有路径和文件扩展名),请在被调用方中使用:

import inspect
filename = inspect.stack()[1].filename 
Run Code Online (Sandbox Code Playgroud)

完整文件名与仅文件名

要检索调用者的文件名,请使用inspect.stack()。此外,以下代码还修剪了开头的路径和完整文件名末尾的文件扩展名:

# Callee.py
import inspect
import os.path

def get_caller_info():
  # first get the full filename (including path and file extension)
  caller_frame = inspect.stack()[1]
  caller_filename_full = caller_frame.filename

  # now get rid of the directory (via basename)
  # then split filename and extension (via splitext)
  caller_filename_only = os.path.splitext(os.path.basename(caller_filename_full))[0]

  # return both filename versions as tuple
  return caller_filename_full, caller_filename_only
Run Code Online (Sandbox Code Playgroud)

然后可以像这样使用它:

# Caller.py
import callee

filename_full, filename_only = callee.get_caller_info()
print(f"> Filename full: {filename_full}")
print(f"> Filename only: {filename_only}")

# Output
# > Filename full: /workspaces/python/caller_filename/caller.py
# > Filename only: caller
Run Code Online (Sandbox Code Playgroud)

官方文档


dux*_*ux2 7

受ThiefMaster的回答启发,但在inspect.getmodule()返回时也可以使用None

frame = inspect.stack()[1]
filename = frame[0].f_code.co_filename
Run Code Online (Sandbox Code Playgroud)


Ara*_*Fey 7

这可以通过inspect模块来完成,特别是inspect.stack

import inspect
import os.path

def get_caller_filepath():
    # get the caller's stack frame and extract its file path
    frame_info = inspect.stack()[1]
    filepath = frame_info[1]  # in python 3.5+, you can use frame_info.filename
    del frame_info  # drop the reference to the stack frame to avoid reference cycles

    # make the path absolute (optional)
    filepath = os.path.abspath(filepath)
    return filepath
Run Code Online (Sandbox Code Playgroud)

示范:

import b

print(b.get_caller_filepath())
# output: D:\Users\Aran-Fey\a.py
Run Code Online (Sandbox Code Playgroud)