检查谁进口了我 [英] inspect who imported me
问题描述
有两个文件:
# the_imported.py
import inspect
imported_by_fname = inspect.currentframe().f_back.f_code.co_filename
print('{} was imported by {}'.format(__name__, imported_by_fname))
并且:
# the_importer.py
import the_imported
在Python 2.7中执行时:
When executed with Python 2.7:
$ python the_importer.py
the_imported was imported by the_importer.py
在使用Python 3.5执行时:
When executed with Python 3.5:
$ python3 the_importer.py
the_imported was imported by <frozen importlib._bootstrap>
<frozen importlib._bootstrap>
的所有奇怪内容是什么? import
和/或inspect
发生了什么,改变了这种行为?我们如何才能使Python 2文件名内省再次在Python 3上正常工作?
What is that weird thing <frozen importlib._bootstrap>
all about? What happened with import
and/or inspect
that changed this behaviour? How can we get that Python 2 filename introspection working again on Python 3?
推荐答案
In Python 3.1 and newer the import machinery is implemented in Python, which makes it possible to access its call stack. To illustrate this, I'll put the following code
from traceback import print_stack
print_stack()
the_imported.py 并将其导入.
在可打印代码的Python 2上
On Python 2 that code prints
File "the_importer.py", line 2, in <module>
import the_imported
File ".../the_imported.py", line 3, in <module>
print_stack()
但是在Python 3上,输出更为冗长:
But on Python 3 the output is much more verbose:
File "the_importer.py", line 2, in <module>
import the_imported
File "<frozen importlib._bootstrap>", line 961, in _find_and_load
File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 677, in exec_module
File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
File ".../the_imported.py", line 2, in <module>
print_stack()
在Python 3.3之前,这些行也包含在跟踪中.
Before Python 3.3, these lines were also included in tracebacks.
要获得所需的结果,您可以在调用堆栈中查找第一帧,其文件名不是以<frozen importlib
开头.
To achieve the desired result you could walk up the call stack to find the first frame, the file name of which doesn't start with <frozen importlib
.
from traceback import extract_stack
for x in extract_stack():
if not x[0].startswith('<frozen importlib'):
print('{} was imported by {}'.format(__name__, x[0]))
break
这篇关于检查谁进口了我的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!