Skip to content

Instantly share code, notes, and snippets.

@DEKHTIARJonathan
Created June 14, 2022 22:06
Show Gist options
  • Save DEKHTIARJonathan/0e2ab643c624c4f1b0ed2b2dbae0b203 to your computer and use it in GitHub Desktop.
Save DEKHTIARJonathan/0e2ab643c624c4f1b0ed2b2dbae0b203 to your computer and use it in GitHub Desktop.
Logging all imports in Python
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