不将其作为参数传递...
例。在 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/