例如,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)
win*_*rrr 17
要获取完整的文件名(带有路径和文件扩展名),请在被调用方中使用:
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)
受ThiefMaster的回答启发,但在inspect.getmodule()返回时也可以使用None:
frame = inspect.stack()[1]
filename = frame[0].f_code.co_filename
Run Code Online (Sandbox Code Playgroud)
这可以通过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)
| 归档时间: |
|
| 查看次数: |
12124 次 |
| 最近记录: |