Created
June 14, 2022 22:06
-
-
Save DEKHTIARJonathan/0e2ab643c624c4f1b0ed2b2dbae0b203 to your computer and use it in GitHub Desktop.
Logging all imports in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import builtins | |
import sys | |
__real_import__ = __import__ | |
__IMPORTED_MODULES__ = [] | |
def __import_debugger__(*args, **kwargs): | |
try: | |
module = args[0] | |
caller = args[1]['__name__'] | |
if module not in __IMPORTED_MODULES__: | |
print("==============================") | |
print(f"Caller: {caller}") | |
print(f"Importing: {module}") | |
print("------------------------------") | |
sys.stdout.flush() | |
__IMPORTED_MODULES__.append(module) # avoid logging an import already in __modules__. | |
except: | |
pass | |
return __real_import__(*args, **kwargs) | |
builtins.__import__ = __import_debugger__ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment