Hook to the first import of the module and print the module path

Hook to the first import and print the module path

TL;DR

motivation

[^ 1]: Exactly on Maya's Python interpreter. [^ 2]: Censored.

code

firstimport_hook.py


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import __builtin__
import types
import copy
import sys

import inspect

# reload()For countermeasures__import__Store after confirming that is Builtin Function.
if isinstance(__import__, types.BuiltinFunctionType):
    _original__import__ = copy.deepcopy(__import__)

#For example, if it is imported hooked by another module,
# _original__import__Can not be defined, so throw an error appropriately
elif '_original__import__' not in globals():
    raise ImportError('Definition of _original__import__ failed.')


def __get_modulefile_from_load_module():
    try:
        #Get the module file to read from
        currentframe = inspect.currentframe()
        module_file = currentframe.f_back.f_back.f_code.co_filename
    finally:
        #Del to correct the reference count.
        del currentframe

    return module_file


def print_modulefile_post_first_import(*args, **kwargs):
    """View module files after initial import"""

    #Get module loading status before importing
    loaded_module_names = sys.modules.keys()

    # __import__Run
    module = _original__import__(*args, **kwargs)

    #Do not process modules that have already been loaded
    if module.__name__ in loaded_module_names:
        return module

    # __file__Do not show the path of modules that do not have
    filepath = getattr(module, '__file__', None)
    if filepath:
        path_from_load_module = __get_modulefile_from_load_module()

        print('%s -> %s' % (path_from_load_module, filepath))

    return module


def enable_import_hook():
    """Enable import hooks"""
    __builtin__.__import__ = print_modulefile_post_first_import


def disable_import_hook():
    """Disable import hooks"""
    __builtin__.__import__ = _original__import__


if __name__ == '__main__':
    #Enable import hook
    enable_import_hook()

    import json
    reload(json)

startup.py


import firstimport_hook
firstimport_hook.enable_import_hook()

Finally

Now, when you import a Python file for the first time, you can print () the path of the loaded module. After that, if you send it to the server appropriately, it will be possible to aggregate.

mel? You don't know ...

Recommended Posts

Hook to the first import of the module and print the module path
[Introduction to Udemy Python3 + Application] 69. Import of absolute path and relative path
Check the path of the Python imported module
To get the path of the currently running python.exe
How to access the global variable of the imported module
[Selenium] How to specify the relative path of chromedriver?
[Python of Hikari-] Chapter 08-03 Module (Import and use of standard library)
Make the display of Python module exceptions easier to understand
I want to know the features of Python and pip
Commands and files to check the version of CentOS Linux
2015-11-26 python> Display the function list of the module> import math> dir (math)
The story of returning to the front line for the first time in 5 years and refactoring Python Django
Find the critical path of PERT using breadth-first search and depth-first search
Note: Get the first and last items of Python OrderedDict non-destructively
[EC2] How to install chrome and the contents of each command
[Introduction to Python] I compared the naming conventions of C # and Python.
First python ② Try to write code while examining the features of python
About the bug that anaconda fails to import numpy and scipy
The first artificial intelligence. How to check the version of Tensorflow installed.
I summarized how to change the boot parameters of GRUB and GRUB2
To improve the reusability and maintainability of workflows created with Luigi
Convert the result of python optparse to dict and utilize it
Test the version of the argparse module
The story of Python and the story of NaN
How to use the optparse module
[Python] The stumbling block of import
First Python 3 ~ The beginning of repetition ~
[Python] How to import the library
Get the first element of queryset
Don't print and import logging for logging
How to use the ConfigParser module
Supplement to the explanation of vscode
[Python Kivy] How to get the file path by dragging and dropping
Ford-Fulkerson Method and Its Applications-Supplement to Chapter 8 of the Algorithm Quick Reference-
[Python] How to specify the window display position and size of matplotlib
I tried to visualize the age group and rate distribution of Atcoder
Python> sys.path> List of strings indicating the path to search for modules
Hook to Shared Library on Linux to interrupt the behavior of existing binaries
The file name was bad in Python and I was addicted to import
I tried to find the optimal path of the dreamland by (quantum) annealing
I tried to extract and illustrate the stage of the story using COTOHA
I tried to verify and analyze the acceleration of Python by Cython
I want to analyze the emotions of people who want to meet and tremble
__Getattr__ and __getattribute__ to customize the acquisition of object attributes by dots
Try to separate the background and moving object of the video with OpenCV
The story of trying to reconnect the client
This and that of the inclusion notation.
Import of japandas with pandas 1.0 and above
Script to change the description of fasta
How to check the version of Django
The story of adding MeCab to ubuntu 16.04
Review the concept and terminology of regression
Coexistence of Flask logging and other module logging
Get the path to the systemd unit file
To import your own module with jupyter
[Python] Import the module one level higher
Print the include header path in clang
The story of trying deep3d and losing
The story of pep8 changing to pycodestyle
Import by directly specifying the directory path
Module import and exception handling in python