__init__.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. from __future__ import print_function
  2. import os.path
  3. import sys
  4. _COLOR_CODES = {
  5. "white": u'\033[0m',
  6. "red": u'\033[31m',
  7. "green": u'\033[32m',
  8. "orange": u'\033[33m',
  9. "blue": u'\033[34m',
  10. "purple": u'\033[35m',
  11. "W": u'\033[0m',
  12. "R": u'\033[31m',
  13. "G": u'\033[32m',
  14. "O": u'\033[33m',
  15. "B": u'\033[34m',
  16. "P": u'\033[35m'
  17. }
  18. def console_log(data, color="white", end="\n"):
  19. """
  20. log data to console.
  21. (if not flush console log, Gitlab-CI won't update logs during job execution)
  22. :param data: data content
  23. :param color: color
  24. """
  25. if color not in _COLOR_CODES:
  26. color = "white"
  27. color_codes = _COLOR_CODES[color]
  28. if isinstance(data, type(b'')):
  29. data = data.decode('utf-8', 'replace')
  30. print(color_codes + data, end=end)
  31. if color not in ["white", "W"]:
  32. # reset color to white for later logs
  33. print(_COLOR_CODES["white"] + u"\r")
  34. sys.stdout.flush()
  35. __LOADED_MODULES = dict()
  36. # we should only load one module once.
  37. # if we load one module twice,
  38. # python will regard the same object loaded in the first time and second time as different objects.
  39. # it will lead to strange errors like `isinstance(object, type_of_this_object)` return False
  40. def load_source(path):
  41. """
  42. Dynamic loading python file. Note that this function SHOULD NOT be used to replace ``import``.
  43. It should only be used when the package path is only available in runtime.
  44. :param path: The path of python file
  45. :return: Loaded object
  46. """
  47. path = os.path.realpath(path)
  48. # load name need to be unique, otherwise it will update the already loaded module
  49. load_name = str(len(__LOADED_MODULES))
  50. try:
  51. return __LOADED_MODULES[path]
  52. except KeyError:
  53. try:
  54. from importlib.machinery import SourceFileLoader
  55. ret = SourceFileLoader(load_name, path).load_module()
  56. except ImportError:
  57. # importlib.machinery doesn't exists in Python 2 so we will use imp (deprecated in Python 3)
  58. import imp
  59. ret = imp.load_source(load_name, path)
  60. __LOADED_MODULES[path] = ret
  61. return ret