1
1
# copy from alas https://github.com/LmeSzinc/AzurLaneAutoScript
2
2
import os
3
3
import re
4
- from typing import Callable , Generic , TypeVar
4
+ from dataclasses import dataclass
5
+ from typing import Callable , Generic , Iterable , TypeVar
5
6
6
7
T = TypeVar ("T" )
7
8
@@ -112,3 +113,58 @@ def poor_yaml_write(data, file, template_file=DEPLOY_TEMPLATE):
112
113
113
114
with open (file , 'w' , encoding = 'utf-8' , newline = '' ) as f :
114
115
f .write (text )
116
+
117
+ @dataclass
118
+ class DataProcessInfo :
119
+ proc : object # psutil.Process or psutil._pswindows.Process
120
+ pid : int
121
+
122
+ @cached_property
123
+ def name (self ):
124
+ try :
125
+ name = self .proc .name ()
126
+ except :
127
+ name = ''
128
+ return name
129
+
130
+ @cached_property
131
+ def cmdline (self ):
132
+ try :
133
+ cmdline = self .proc .cmdline ()
134
+ except :
135
+ # psutil.AccessDenied
136
+ # # NoSuchProcess: process no longer exists (pid=xxx)
137
+ cmdline = []
138
+ cmdline = ' ' .join (cmdline ).replace (r'\\' , '/' ).replace ('\\ ' , '/' )
139
+ return cmdline
140
+
141
+ def __str__ (self ):
142
+ # Don't print `proc`, it will take some time to get process properties
143
+ return f'DataProcessInfo(name="{ self .name } ", pid={ self .pid } , cmdline="{ self .cmdline } ")'
144
+
145
+ __repr__ = __str__
146
+
147
+
148
+ def iter_process () -> Iterable [DataProcessInfo ]:
149
+ try :
150
+ import psutil
151
+ except ModuleNotFoundError :
152
+ return
153
+
154
+ if psutil .WINDOWS :
155
+ # Since this is a one-time-usage, we access psutil._psplatform.Process directly
156
+ # to bypass the call of psutil.Process.is_running().
157
+ # This only costs about 0.017s.
158
+ for pid in psutil .pids ():
159
+ proc = psutil ._psplatform .Process (pid )
160
+ yield DataProcessInfo (
161
+ proc = proc ,
162
+ pid = proc .pid ,
163
+ )
164
+ else :
165
+ # This will cost about 0.45s, even `attr` is given.
166
+ for proc in psutil .process_iter ():
167
+ yield DataProcessInfo (
168
+ proc = proc ,
169
+ pid = proc .pid ,
170
+ )
0 commit comments