好的。我想到了。此代碼可以駐留在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