-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodels.py
More file actions
80 lines (66 loc) · 2.3 KB
/
models.py
File metadata and controls
80 lines (66 loc) · 2.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# coding=utf-8
import socket
import time
class Process(object):
"""Контейнер для данных о процессе"""
dict_fields = (
'pid',
'cmd',
'args',
'kwargs',
'spawned_at',
'host',
)
# noinspection PyProtectedMember
def __init__(self, cmd=None, process_obj=None, keep_unfilled=False):
"""
Используется в двух сценариях: обертка над объектом multiprocessing.Process либо внутри
метода from_record для создания пустого контейнера и дальнейшего заполнения данными из таблицы.
В последнем случае нужно указать флаг keep_unfilled
:param cmd: str
:param keep_unfilled: bool
:param process_obj: multiprocessing.Process object
"""
assert (cmd is not None and process_obj is not None) or keep_unfilled
self._waiting = True
if keep_unfilled:
return
self.pid = process_obj.pid
self.cmd = cmd
self.args = process_obj._args
self.kwargs = process_obj._kwargs
self.host = socket.getfqdn()
self.spawned_at = time.time()
def set_as_running(self):
self._waiting = False
@classmethod
def from_record(cls, waiting=False, **kwargs):
obj = cls(keep_unfilled=True)
for field in cls.dict_fields:
setattr(obj, field, kwargs[field])
if not waiting:
obj.set_as_running()
return obj
@property
def waisted_time_sec(self):
if not self._waiting:
return None
now = time.time()
return now - self.spawned_at
def _asdict(self):
return {k: getattr(self, k) for k in self.dict_fields}
def __str__(self):
return (
'Process('
'pid={self.pid}, '
'cmd={self.cmd}, '
'args={self.args}, '
'kwargs={self.kwargs}, '
'{time_field}'
')'
).format(
self=self,
time_field=(
'lifetime_sec=%s' if not self._waiting else 'waisted_time_sec=%s'
) % int(time.time() - self.spawned_at)
)