如何获得来电者';s文件名,python中的方法名

如何获得来电者';s文件名,python中的方法名,python,Python,例如,a.boo方法调用b.foo方法。在b.foo方法中,如何获取a的文件名(我不想将\uuuu file\uuuu传递到b.foo方法).您可以使用检查模块来实现这一点: frame = inspect.stack()[1] module = inspect.getmodule(frame[0]) filename = module.__file__ 您可以使用回溯模块: import traceback 您可以按如下方式打印回描: print traceback.format_stac

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

您可以使用
检查
模块来实现这一点:

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

您可以使用
回溯
模块:

import traceback
您可以按如下方式打印回描:

print traceback.format_stack()

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

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

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

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

import inspect
print inspect.stack()[1][1]
框架中的第二项已经是调用者的文件名,或者这不是健壮的吗?

这可以通过模块完成,具体来说:

演示:

import b

print(b.get_caller_filepath())
# output: D:\Users\Aran-Fey\a.py
Python 3.5+ 一班轮 要获取完整文件名(带有路径和文件扩展名),请在被调用方中使用:

import inspect
filename = inspect.stack()[1].filename 
完整文件名与仅文件名 要检索调用方的文件名,请使用。此外,以下代码还修剪完整文件名开头的路径和结尾的文件扩展名:

# 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
公文
  • :从文件名中删除路径(仍包括扩展名)
  • :拆分文件名和文件扩展名

谢谢你的回答,我发现现在这里对我来说是最好的:
inspect.getmodule()
在某些情况下可能返回
None
,因此一种更可靠的方法是:
filename=frame[0].f_code.co_filename
为什么不只是
filename=frame[1]
(或者在python 3.5+中是
frame.filename
)?当然,它是健壮的,只是可读性不强。因此,
inspect.stack()[1].filename
是Python 3.5支持的首选语法。
# 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