假设我有一个名为 的 python 模块pymodule
,它驻留在名为pymodule.py
.
此外,假设pymodule
由多个其它Python程序的进口,例如program0.py
,program1.py
,和program2.py
。
有没有我可以编写的代码pymodule.py
来在运行时确定导入文件的名称?在这个例子中,我们最终会得到两种/path/to/program0.py
,/path/to/program1.py
或者/path/to/program2.py
,取决于其这三个项目的运行。
当然,可能有一组嵌套的导入已在其中pymodule
导入,因此在一般情况下,我希望在运行时获得整个导入祖先文件名组。
有没有办法在python3中做到这一点?
非常感谢你。
好的。我想到了。此代码可以驻留在pymodule.py
...
# This is the "parent" of the current module.
# `sys._getframe(0)` would be `pymodule.py`.
f = sys._getframe(1)
while f is not None:
print('filename: {}'.format(f.f_code.co_filename)
f = f.f_back
如果/path/to/program0.py
正在运行,它会打印出以下内容...
filename: <frozen importlib._bootstrap>
filename: <frozen importlib._bootstrap_external>
filename: <frozen importlib._bootstrap>
filename: <frozen importlib._bootstrap>
filename: <frozen importlib._bootstrap>
filename: /path/to/program0.py
所以,我所要做的就是忽略以 开头的项目<frozen ...
,我将获得祖先文件名。这是一个可以做到的函数......
def ancestor_importers():
ancestors = []
# Start with item number 2 here, because we're
# inside of a function. Assume this function
# resides at the top level of `pymodule`. If not,
# the argument of sys._getframe(2) needs to be
# adjusted accordingly.
f = sys._getframe(2)
while f is not None:
fn = f.f_code.co_filename
if not fn.startswith('<frozen '):
ancestors.append(fn)
f = f.f_back
return ancestors
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句