45

例如,a.boo方法调用b.foo方法。在b.foo方法中,我怎样才能得到一个文件名(我不想传递__file__b.foo方法)......

4

6 回答 6

56

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

frame = inspect.stack()[1]
module = inspect.getmodule(frame[0])
filename = module.__file__
于 2012-12-04T09:08:11.553 回答
20

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_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

然后可以像这样使用它:

# 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

官方文档

于 2020-02-19T10:15:03.193 回答
18

受 ThiefMaster 的回答启发,但如果inspect.getmodule()返回也可以None

frame = inspect.stack()[1]
filename = frame[0].f_code.co_filename
于 2018-09-06T10:31:42.313 回答
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

示范:

import b

print(b.get_caller_filepath())
# output: D:\Users\Aran-Fey\a.py
于 2019-04-02T08:12:43.630 回答
3

您可以使用该traceback模块:

import traceback

你可以像这样打印回溯:

print traceback.format_stack()

我已经好几年没用过了,但这应该足以让你开始。

于 2012-12-04T09:09:11.097 回答
2

阅读所有这些解决方案,似乎这也有效?

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

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

于 2019-01-30T17:14:48.637 回答