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

时间:2012-12-04 09:06:13

标签: python

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

6 个答案:

答案 0 :(得分:30)

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

frame = inspect.stack()[1]
module = inspect.getmodule(frame[0])
filename = module.__file__

答案 1 :(得分:7)

Python 3.5 +

单行

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

import inspect
filename = inspect.stack()[1].filename 

仅文件名

要检索呼叫者的文件名,请使用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_full_filename = caller_frame.filename

  # now get rid of the directory and file extension
  caller_filename = os.path.splitext(os.path.basename(caller_full_filename))[0]

  # return all info as tuple
  return caller_full_filename, caller_filename

然后可以像这样使用它:

# Caller.py
import callee

full_filename, filename = callee.get_caller_info()
print(f"> Full filename: {full_filename}")
print(f"> Short filename: {filename}")

# Output
# > Full filename: /workspaces/python/caller_filename/caller.py
# > Short filename: caller

其他来源:

答案 2 :(得分:3)

受到ThiefMaster的回答的启发,但是如果inspect.getmodule()返回None也可以起作用:

frame = inspect.stack()[1]
filename = frame[0].f_code.co_filename

答案 3 :(得分:1)

您可以使用traceback模块:

import traceback

你可以像这样打印背面痕迹:

print traceback.format_exc()

多年来我没有用过这个,但这应该足以让你开始。

答案 4 :(得分:0)

阅读所有这些解决方案,看来这也可行吗?

import inspect
print inspect.stack()[1][1]

框架中的第二项已经是调用者的文件名,还是不够可靠?

答案 5 :(得分:0)

这可以通过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

演示:

import b

print(b.get_caller_filepath())
# output: D:\Users\Aran-Fey\a.py
相关问题