You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让a.py中的函数获取调用方b.py的文件名?

解决方案

可以利用Python的inspect模块获取调用栈信息,直接从调用上下文里拿到调用者的文件名,无需在调用时手动传递参数。

a.py 代码实现

import inspect

def foo():
    # 取调用栈的第2个帧(索引1),对应调用foo()的上下文
    caller_frame = inspect.stack()[1]
    # 获取调用者的文件名
    caller_file = caller_frame.filename
    print(f"调用者文件名: {caller_file}")

b.py 代码实现

from a import foo

# 直接调用即可,无需额外传递参数
foo()

原理说明

inspect.stack()会返回当前程序的调用栈列表,每个元素包含了栈帧的详细信息:

  • 索引0是foo()函数自身的栈帧
  • 索引1就是调用foo()的代码所在的栈帧,从这个帧的filename属性就能直接获取调用者脚本(也就是b.py)的路径/文件名。

如果只需要纯文件名(不带路径),可以结合os.path.basename()处理:

import os
import inspect

def foo():
    caller_frame = inspect.stack()[1]
    caller_filename = os.path.basename(caller_frame.filename)
    print(f"调用者文件名: {caller_filename}")

内容的提问来源于stack exchange,提问作者mathbike

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 23:55:20