module_paths.py 2.3 KB

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