在python中,如果一个模块调用另一个模块的功能,该功能是否可以访问第一个模块的文件路径?
问题描述:
没有将其作为参数传递...
Without passing it as a parameter...
例如在test1.py中:
Ex. In test1.py:
def function():
print (?????)
和在test2.py
and in test2.py
import test1
test1.function()
有可能写?????所以运行test2.py会打印出"test2.py"或完整的文件路径? __ 文件 __ 将打印出"test1.py".
Is it possible to write ????? so running test2.py prints out 'test2.py' or the full filepath? __file__ would print out 'test1.py'.
答
可以使用 test2.py
看起来很像您的,但已修复import
:
test2.py
looks much like yours but with the the import
fixed:
% cat test2.py
#!/usr/bin/env python
import test1
test1.function()
试运行...
% ./test2.py
Called from within: ./test2.py
N.B:
CPython实现细节:此函数应仅用于内部目的和专用目的.不能保证它在所有Python实现中都存在.
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.