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

Python:从模块内部获取导入该模块的文件路径

获取导入当前模块的文件路径的实现方法

方法1:使用inspect模块(推荐)

inspect.stack()可获取当前调用栈信息,栈的第二个元素(索引1)对应调用当前模块的代码帧,从中能提取调用文件的路径。

示例代码(你的模块文件,比如mymodule.py):

import inspect
import os

def get_caller_dir():
    # 跳过当前函数和模块自身的帧,取调用方的栈帧
    caller_frame = inspect.stack()[1]
    caller_file_path = caller_frame.filename
    # 处理交互式环境调用的情况
    if caller_file_path == '<stdin>':
        return os.getcwd()
    # 返回调用文件所在的文件夹路径
    return os.path.dirname(os.path.abspath(caller_file_path))

调用示例(比如test.py,和模块不在同一文件夹):

import mymodule
print(mymodule.get_caller_dir())  # 输出test.py所在的文件夹路径

此方法兼容性好,性能开销极小,适合大多数场景。

方法2:使用sys._getframe()

直接获取当前栈帧的上一级帧,更轻量,但属于CPython私有API,其他Python实现(如PyPy)可能不支持。

示例代码(你的模块文件):

import sys
import os

def get_caller_dir():
    caller_frame = sys._getframe(1)
    caller_file_path = caller_frame.f_code.co_filename
    if caller_file_path == '<stdin>':
        return os.getcwd()
    return os.path.dirname(os.path.abspath(caller_file_path))

注意事项

  • 若调用方在交互式Python环境中,filename会返回<stdin>,此时返回当前工作目录是合理选择。
  • 栈帧操作仅在确实需要获取调用上下文时使用,避免不必要的上下文依赖。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 00:37:38