Format: text/x-python
⬇ Download File (2.3 KB)
   1  """Utility functions for finding modules
   2  
   3  Utility functions for finding modules on sys.path.
   4  
   5  """
   6  #-----------------------------------------------------------------------------
   7  # Copyright (c) 2011, the IPython Development Team.
   8  #
   9  # Distributed under the terms of the Modified BSD License.
  10  #
  11  # The full license is in the file COPYING.txt, distributed with this software.
  12  #-----------------------------------------------------------------------------
  13  
  14  #-----------------------------------------------------------------------------
  15  # Imports
  16  #-----------------------------------------------------------------------------
  17  
  18  # Stdlib imports
  19  import importlib
  20  import sys
  21  
  22  # Third-party imports
  23  
  24  # Our own imports
  25  
  26  
  27  #-----------------------------------------------------------------------------
  28  # Globals and constants
  29  #-----------------------------------------------------------------------------
  30  
  31  #-----------------------------------------------------------------------------
  32  # Local utilities
  33  #-----------------------------------------------------------------------------
  34  
  35  #-----------------------------------------------------------------------------
  36  # Classes and functions
  37  #-----------------------------------------------------------------------------
  38  
  39  def find_mod(module_name):
  40      """
  41      Find module `module_name` on sys.path, and return the path to module `module_name`.
  42  
  43      * If `module_name` refers to a module directory, then return path to `__init__` file.
  44          * If `module_name` is a directory without an __init__file, return None.
  45  
  46      * If module is missing or does not have a `.py` or `.pyw` extension, return None.
  47          * Note that we are not interested in running bytecode.
  48  
  49      * Otherwise, return the fill path of the module.
  50  
  51      Parameters
  52      ----------
  53      module_name : str
  54  
  55      Returns
  56      -------
  57      module_path : str
  58          Path to module `module_name`, its __init__.py, or None,
  59          depending on above conditions.
  60      """
  61      spec = importlib.util.find_spec(module_name)
  62      module_path = spec.origin
  63      if module_path is None:
  64          if spec.loader in sys.meta_path:
  65              return spec.loader
  66          return None
  67      else:
  68          split_path = module_path.split(".")
  69          if split_path[-1] in ["py", "pyw"]:
  70              return module_path
  71          else:
  72              return None
  73