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 1.3 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. # -*- coding: utf-8 -*-
  2. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  3. #
  4. # Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
  5. #
  6. # Unless required by applicable law or agreed to in writing,
  7. # software distributed under the License is distributed on an
  8. # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. import importlib.util
  10. import os
  11. import types
  12. from contextlib import contextmanager
  13. from typing import Iterator
  14. def load_module(name: str, path: str) -> types.ModuleType:
  15. r"""Loads module specified by name and path.
  16. Args:
  17. name: module name.
  18. path: module path.
  19. """
  20. spec = importlib.util.spec_from_file_location(name, path)
  21. module = importlib.util.module_from_spec(spec)
  22. spec.loader.exec_module(module)
  23. return module
  24. def check_module_exists(module: str) -> bool:
  25. r"""Checks whether python module exists or not.
  26. Args:
  27. module: name of module.
  28. """
  29. return importlib.util.find_spec(module) is not None
  30. @contextmanager
  31. def cd(target: str) -> Iterator[None]:
  32. """Changes current directory to target.
  33. Args:
  34. target: target directory.
  35. """
  36. prev = os.getcwd()
  37. os.chdir(os.path.expanduser(target))
  38. try:
  39. yield
  40. finally:
  41. os.chdir(prev)