utils.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. # copy from alas https://github.com/LmeSzinc/AzurLaneAutoScript
  2. import os
  3. import re
  4. from dataclasses import dataclass
  5. from typing import Callable, Generic, Iterable, TypeVar
  6. T = TypeVar("T")
  7. DEPLOY_CONFIG = './config/deploy.yaml'
  8. DEPLOY_TEMPLATE = './deploy/template'
  9. class cached_property(Generic[T]):
  10. """
  11. cached-property from https://github.com/pydanny/cached-property
  12. Add typing support
  13. A property that is only computed once per instance and then replaces itself
  14. with an ordinary attribute. Deleting the attribute resets the property.
  15. Source: https://github.com/bottlepy/bottle/commit/fa7733e075da0d790d809aa3d2f53071897e6f76
  16. """
  17. def __init__(self, func: Callable[..., T]):
  18. self.func = func
  19. def __get__(self, obj, cls) -> T:
  20. if obj is None:
  21. return self
  22. value = obj.__dict__[self.func.__name__] = self.func(obj)
  23. return value
  24. def iter_folder(folder, is_dir=False, ext=None):
  25. """
  26. Args:
  27. folder (str):
  28. is_dir (bool): True to iter directories only
  29. ext (str): File extension, such as `.yaml`
  30. Yields:
  31. str: Absolute path of files
  32. """
  33. for file in os.listdir(folder):
  34. sub = os.path.join(folder, file)
  35. if is_dir:
  36. if os.path.isdir(sub):
  37. yield sub.replace('\\\\', '/').replace('\\', '/')
  38. elif ext is not None:
  39. if not os.path.isdir(sub):
  40. _, extension = os.path.splitext(file)
  41. if extension == ext:
  42. yield os.path.join(folder, file).replace('\\\\', '/').replace('\\', '/')
  43. else:
  44. yield os.path.join(folder, file).replace('\\\\', '/').replace('\\', '/')
  45. def poor_yaml_read(file):
  46. """
  47. Poor implementation to load yaml without pyyaml dependency, but with re
  48. Args:
  49. file (str):
  50. Returns:
  51. dict:
  52. """
  53. if not os.path.exists(file):
  54. return {}
  55. data = {}
  56. regex = re.compile(r'^(.*?):(.*?)$')
  57. with open(file, 'r', encoding='utf-8') as f:
  58. for line in f.readlines():
  59. line = line.strip('\n\r\t ').replace('\\', '/')
  60. if line.startswith('#'):
  61. continue
  62. result = re.match(regex, line)
  63. if result:
  64. k, v = result.group(1), result.group(2).strip('\n\r\t\' ')
  65. if v:
  66. if v.lower() == 'null':
  67. v = None
  68. elif v.lower() == 'false':
  69. v = False
  70. elif v.lower() == 'true':
  71. v = True
  72. elif v.isdigit():
  73. v = int(v)
  74. data[k] = v
  75. return data
  76. def poor_yaml_write(data, file, template_file=DEPLOY_TEMPLATE):
  77. """
  78. Args:
  79. data (dict):
  80. file (str):
  81. template_file (str):
  82. """
  83. with open(template_file, 'r', encoding='utf-8') as f:
  84. text = f.read().replace('\\', '/')
  85. for key, value in data.items():
  86. if value is None:
  87. value = 'null'
  88. elif value is True:
  89. value = "true"
  90. elif value is False:
  91. value = "false"
  92. text = re.sub(f'{key}:.*?\n', f'{key}: {value}\n', text)
  93. with open(file, 'w', encoding='utf-8', newline='') as f:
  94. f.write(text)
  95. @dataclass
  96. class DataProcessInfo:
  97. proc: object # psutil.Process or psutil._pswindows.Process
  98. pid: int
  99. @cached_property
  100. def name(self):
  101. try:
  102. name = self.proc.name()
  103. except:
  104. name = ''
  105. return name
  106. @cached_property
  107. def cmdline(self):
  108. try:
  109. cmdline = self.proc.cmdline()
  110. except:
  111. # psutil.AccessDenied
  112. # # NoSuchProcess: process no longer exists (pid=xxx)
  113. cmdline = []
  114. cmdline = ' '.join(cmdline).replace(r'\\', '/').replace('\\', '/')
  115. return cmdline
  116. def __str__(self):
  117. # Don't print `proc`, it will take some time to get process properties
  118. return f'DataProcessInfo(name="{self.name}", pid={self.pid}, cmdline="{self.cmdline}")'
  119. __repr__ = __str__
  120. def iter_process() -> Iterable[DataProcessInfo]:
  121. try:
  122. import psutil
  123. except ModuleNotFoundError:
  124. return
  125. if psutil.WINDOWS:
  126. # Since this is a one-time-usage, we access psutil._psplatform.Process directly
  127. # to bypass the call of psutil.Process.is_running().
  128. # This only costs about 0.017s.
  129. for pid in psutil.pids():
  130. proc = psutil._psplatform.Process(pid)
  131. yield DataProcessInfo(
  132. proc=proc,
  133. pid=proc.pid,
  134. )
  135. else:
  136. # This will cost about 0.45s, even `attr` is given.
  137. for proc in psutil.process_iter():
  138. yield DataProcessInfo(
  139. proc=proc,
  140. pid=proc.pid,
  141. )