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.

pymod.py 2.6 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. # Copyright (c) Alibaba, Inc. and its affiliates.
  2. import ast
  3. import os
  4. import os.path as osp
  5. import sys
  6. import types
  7. from importlib import import_module
  8. from maas_lib.utils.logger import get_logger
  9. logger = get_logger()
  10. def import_modules_from_file(py_file: str):
  11. """ Import module from a certrain file
  12. Args:
  13. py_file: path to a python file to be imported
  14. Return:
  15. """
  16. dirname, basefile = os.path.split(py_file)
  17. if dirname == '':
  18. dirname == './'
  19. module_name = osp.splitext(basefile)[0]
  20. sys.path.insert(0, dirname)
  21. validate_py_syntax(py_file)
  22. mod = import_module(module_name)
  23. sys.path.pop(0)
  24. return module_name, mod
  25. def import_modules(imports, allow_failed_imports=False):
  26. """Import modules from the given list of strings.
  27. Args:
  28. imports (list | str | None): The given module names to be imported.
  29. allow_failed_imports (bool): If True, the failed imports will return
  30. None. Otherwise, an ImportError is raise. Default: False.
  31. Returns:
  32. list[module] | module | None: The imported modules.
  33. Examples:
  34. >>> osp, sys = import_modules(
  35. ... ['os.path', 'sys'])
  36. >>> import os.path as osp_
  37. >>> import sys as sys_
  38. >>> assert osp == osp_
  39. >>> assert sys == sys_
  40. """
  41. if not imports:
  42. return
  43. single_import = False
  44. if isinstance(imports, str):
  45. single_import = True
  46. imports = [imports]
  47. if not isinstance(imports, list):
  48. raise TypeError(
  49. f'custom_imports must be a list but got type {type(imports)}')
  50. imported = []
  51. for imp in imports:
  52. if not isinstance(imp, str):
  53. raise TypeError(
  54. f'{imp} is of type {type(imp)} and cannot be imported.')
  55. try:
  56. imported_tmp = import_module(imp)
  57. except ImportError:
  58. if allow_failed_imports:
  59. logger.warning(f'{imp} failed to import and is ignored.')
  60. imported_tmp = None
  61. else:
  62. raise ImportError
  63. imported.append(imported_tmp)
  64. if single_import:
  65. imported = imported[0]
  66. return imported
  67. def validate_py_syntax(filename):
  68. with open(filename, 'r', encoding='utf-8') as f:
  69. # Setting encoding explicitly to resolve coding issue on windows
  70. content = f.read()
  71. try:
  72. ast.parse(content)
  73. except SyntaxError as e:
  74. raise SyntaxError('There are syntax errors in config '
  75. f'file {filename}: {e}')

致力于通过开放的社区合作,开源AI模型以及相关创新技术,推动基于模型即服务的生态繁荣发展