filesystem.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import os
  2. EXCLUDED_MODULE_NAMES = ['__init__.py']
  3. def is_package(path):
  4. """Checks if path string is a package"""
  5. return os.path.exists(os.path.join(path, '__init__.py'))
  6. def is_module(path):
  7. """Checks if path string is a module"""
  8. return path.endswith('.py')
  9. def get_name(path):
  10. filename = os.path.basename(path)
  11. name, _ = os.path.splitext(filename)
  12. return name
  13. def find_modules(path):
  14. """Finds all modules located on a path"""
  15. for pathname in os.listdir(path):
  16. if pathname in EXCLUDED_MODULE_NAMES:
  17. continue
  18. full_path = os.path.join(path, pathname)
  19. if os.path.isfile(full_path) and is_module(full_path):
  20. yield full_path
  21. def find_packages(path):
  22. """Finds all packages located on a path"""
  23. for pathname in os.listdir(path):
  24. full_path = os.path.join(path, pathname)
  25. if os.path.isdir(full_path) and is_package(full_path):
  26. yield full_path
  27. def recursive_find_packages(path):
  28. """Recursively finds all packages located on a path"""
  29. for pkg in find_packages(path):
  30. yield pkg
  31. for sub_pkg in recursive_find_packages(pkg):
  32. yield sub_pkg
  33. def recursive_find_modules(path):
  34. """Recursively finds all modules located on a path"""
  35. for module_path in find_modules(path):
  36. yield module_path
  37. for pkg_path in recursive_find_packages(path):
  38. for module_path in find_modules(pkg_path):
  39. yield module_path