You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

tools.py 969 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. # -*- coding: utf-8 -*-
  2. import importlib.util
  3. import os
  4. import types
  5. from contextlib import contextmanager
  6. from typing import Iterator
  7. def load_module(name: str, path: str) -> types.ModuleType:
  8. r"""Loads module specified by name and path.
  9. Args:
  10. name: module name.
  11. path: module path.
  12. """
  13. spec = importlib.util.spec_from_file_location(name, path)
  14. module = importlib.util.module_from_spec(spec)
  15. spec.loader.exec_module(module)
  16. return module
  17. def check_module_exists(module: str) -> bool:
  18. r"""Checks whether python module exists or not.
  19. Args:
  20. module: name of module.
  21. """
  22. return importlib.util.find_spec(module) is not None
  23. @contextmanager
  24. def cd(target: str) -> Iterator[None]:
  25. """Changes current directory to target.
  26. Args:
  27. target: target directory.
  28. """
  29. prev = os.getcwd()
  30. os.chdir(os.path.expanduser(target))
  31. try:
  32. yield
  33. finally:
  34. os.chdir(prev)