python - 在 python 中,如果一个模块调用另一个模块的函数,该函数是否可以访问第一个模块的文件路径?

标签 python module filepath

不将其作为参数传递...

例。在 test1.py 中:

def function():
    print (?????)

并在 test2.py 中

import test1

test1.function()

可以这样写吗?????所以运行 test2.py 会打印出“test2.py”或完整的文件路径? __file__ 将打印出“test1.py”。

最佳答案

这可以通过使用 sys._getframe() 来实现:

% cat test1.py
#!/usr/bin/env python

import sys

def function():
    print 'Called from within:', sys._getframe().f_back.f_code.co_filename

test2.py 看起来很像你的,但 import 已修复:

% cat test2.py
#!/usr/bin/env python

import test1

test1.function()

测试运行...

% ./test2.py 
Called from within: ./test2.py

注意:

CPython implementation detail: This function should be used for internal and specialized purposes only. It is not guaranteed to exist in all implementations of Python.

关于python - 在 python 中,如果一个模块调用另一个模块的函数,该函数是否可以访问第一个模块的文件路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7025538/

相关文章:

Python 检测并检索打开的 csv 文件的文件名

javascript - 带有 AJAX post 的 Flask 应用程序给出 404(未找到)

python - 进行PCA前后的数据维度

include - NMAKE在子文件夹中找不到包含文件

android - 从录制的视频中获取路径

python - 哪种动态语言可以轻松使用其他语言的库?

python - 使图例对应于matplotlib中散点的颜色

python - "python setup.py install"不创建入口 pip

Javascript 模块语法错误 : Cannot use import statement outside a module

c++ - C++ 嵌入式应用程序是否应该为内置 C++ 类型使用带有 typedef 的通用 header ?