-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexecution.py
114 lines (87 loc) · 3.12 KB
/
execution.py
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
import abc
import os
import queue
import signal
import sys
import threading
class ProcessWrapper(metaclass=abc.ABCMeta):
process = None
output = None
command_identifier = None
finish_listeners = None
def __init__(self, command, command_identifier, working_directory):
self.command_identifier = command_identifier
self.finish_listeners = []
self.init_process(command, working_directory)
self.output = queue.Queue()
read_output_thread = threading.Thread(target=self.pipe_process_output, args=())
read_output_thread.start()
notify_finish_thread = threading.Thread(target=self.notify_finished)
notify_finish_thread.start()
@abc.abstractmethod
def pipe_process_output(self):
pass
@abc.abstractmethod
def init_process(self, command, working_directory):
pass
@abc.abstractmethod
def write_to_input(self, value):
pass
@abc.abstractmethod
def wait_finish(self):
pass
def get_process_id(self):
return self.process.pid
def is_finished(self):
return self.process.poll() is not None
def get_return_code(self):
return self.process.returncode
def stop(self):
if not self.is_finished():
if not sys.platform.startswith('win'):
group_id = os.getpgid(self.get_process_id())
os.killpg(group_id, signal.SIGTERM)
class KillChildren(object):
def finished(self):
try:
os.killpg(group_id, signal.SIGKILL)
except ProcessLookupError:
# probably there are no children left
pass
self.add_finish_listener(KillChildren())
else:
self.process.terminate()
self.output.put("\n>> STOPPED BY USER\n")
def kill(self):
if not self.is_finished():
if not sys.platform.startswith('win'):
group_id = os.getpgid(self.get_process_id())
os.killpg(group_id, signal.SIGKILL)
self.output.put("\n>> KILLED\n")
else:
subprocess.Popen("taskkill /F /T /PID " + self.get_process_id())
def read(self):
while True:
try:
result = self.output.get(True, 0.2)
try:
added_text = result
while added_text:
added_text = self.output.get_nowait()
result += added_text
except queue.Empty:
pass
return result
except queue.Empty:
if self.is_finished():
break
def add_finish_listener(self, listener):
self.finish_listeners.append(listener)
if self.is_finished():
self.notify_finished()
def notify_finished(self):
self.wait_finish()
for listener in self.finish_listeners:
listener.finished()
def get_command_identifier(self):
return self.command_identifier