-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommand_line_wrapper.py
More file actions
265 lines (230 loc) · 7.58 KB
/
command_line_wrapper.py
File metadata and controls
265 lines (230 loc) · 7.58 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
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
import sys
import subprocess
import queue
import os
import signal
import threading
import weakref
from functools import wraps
from collections import namedtuple, deque
class CommandLineWrapper:
"""Wraps a command line application. Redirects stdin, stdout and stderr
through pipes. Reads stdout and stderr asynchronously.
>>> c = CommandLineWrapper('cmd', encoding='cp866')
>>> c.stop()
>>> c.communicate('echo Hello World!')
Traceback (most recent call last):
...
RuntimeError: The process is not running.
>>> c.start()
>>> out = c.communicate('echo Hello World!')
>>> assert 'Hello World!' in out
>>> out = c.communicate('AaaazzzZ')
>>> assert c._STDERR_PREFIX in out
>>> c.stop()
>>> c.stop()
Traceback (most recent call last):
...
RuntimeError: The process is not running.
>>> c.start()
>>> c.start()
Traceback (most recent call last):
...
RuntimeError: Already started.
>>> c.stop()
Context manager
>>> cc = None
>>> with CommandLineWrapper('cmd', encoding='cp866') as c:
... cc = c
... assert 'AAAAAA' in c.communicate('echo AAAAAA')
>>> assert not cc.is_running
"""
_CHANNELS = namedtuple('CHANNELS', 'stdout stderr')(1, 2)
_STDERR_PREFIX = 'STDERROR=> '
def __init__(self, *process_args, workdir=None, encoding='utf-8', start=True, startupinfo=None):
if startupinfo is None and sys.platform == 'win32':
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
self._startupinfo = startupinfo
self._process = None
self._workdir = workdir
self._encoding = encoding
self._process_args = process_args
self._q = queue.Queue()
self._handlers = weakref.WeakValueDictionary()
if start:
self.start()
def start(self):
if self.is_running:
raise RuntimeError('Already started.')
self._process = subprocess.Popen(self._process_args,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
cwd=self._workdir,
startupinfo=self._startupinfo,
bufsize=0)
self._handle_output(self._CHANNELS.stdout, self._process.stdout)
self._handle_output(self._CHANNELS.stderr, self._process.stderr)
def stop(self):
self._raise_if_not_running()
self._process.terminate()
self._process.wait()
self._process = None
def kill(self):
if sys.platform == 'win32':
import _winapi
handle = _winapi.OpenProcess(1, False, self._process.pid)
_winapi.TerminateProcess(handle, -1)
_winapi.CloseHandle(handle)
else:
os.kill(self.process.pid, signal.SIGKILL)
def _create_handler(self, channel, buffer):
encoding = self._encoding
buffer = weakref.proxy(buffer)
self = weakref.proxy(self)
def handler():
with open(buffer.fileno(), 'rb', closefd=False) as output:
try:
while (self.is_running and not self._q.full()):
buf = output.read1(8192)
if buf:
try:
text = str(buf, encoding)
text = text.replace('\r', '') # Windows
except UnicodeDecodeError:
print('\nWrong encoding: %s\n' % encoding)
raise
item = (channel, text)
self._q.put(item)
except ReferenceError:
return
return handler
def _handle_output(self, channel, buffer):
if channel in self._handlers:
raise RuntimeError('Channel %s is already handled.' % channel)
handler = self._create_handler(channel, buffer)
started_handler = self._run_handler(handler)
if not started_handler:
raise RuntimeError('_run_handler() must return an object')
self._handlers[channel] = started_handler
def _run_handler(self, handler):
threaded_handler = threading.Thread(target=handler, daemon=True)
threaded_handler.start()
return threaded_handler
def item_to_text(self, item):
channel, text = item
if channel == self._CHANNELS.stderr:
text = self._STDERR_PREFIX + text.replace('\n', '\n' + self._STDERR_PREFIX)
return text
def _gen_output(self, timeout=0.1):
try:
while self.is_running:
item = self._q.get(timeout=timeout)
yield self.item_to_text(item)
except queue.Empty:
raise StopIteration
def get_output(self, timeout=0.1):
self._raise_if_not_running()
return ''.join(item for item in self._gen_output(timeout))
def run_command(self, command):
self._raise_if_not_running()
self._process.stdin.write(bytes(str(command) + '\n', self._encoding))
def communicate(self, input=None):
if input:
self.run_command(input)
return self.get_output()
def _raise_if_not_running(self):
if not self.is_running:
raise RuntimeError('The process is not running.')
@property
def is_running(self):
if self._process is None:
return False
return self._process.poll() is None
def __enter__(self):
if not self.is_running:
self.start()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if self.is_running:
self.stop()
def __del__(self):
try:
self.stop()
except:
pass
class History:
"""
>>> h = History()
>>> class Foo:
... @staticmethod
... @h
... def spam(x):
... print(x)
>>> a = Foo()
>>> a.spam('one')
one
>>> a.spam('two')
two
>>> h.add('three')
>>> print(list(h.items))
['one', 'two', 'three']
>>> h.get_prev()
'three'
>>> h.get_next()
'three'
>>> h.get_prev()
'two'
>>> h.get_next()
'three'
>>> h.get_prev()
'two'
>>> h.get_prev()
'one'
>>> h.get_prev()
'one'
>>> h.get_next()
'two'
>>> h.get_next()
'three'
>>> h.get_next()
'three'
>>> h.add('three')
>>> print(list(h.items))
['one', 'two', 'three']
"""
def __init__(self, maxlen=999):
self.items = deque(maxlen=maxlen)
self._index = 0
def add(self, item):
if not item:
return
if not self.items or self.items[-1] != item:
self.items.append(item)
self._index = len(self.items)
def get_prev(self):
if not self.items:
return None
self.index -= 1
return self.items[self.index]
def get_next(self):
if not self.items:
return None
self.index += 1
if self.index >= len(self.items):
return self.items[-1]
return self.items[self.index]
@property
def index(self):
return self._index
@index.setter
def index(self, val):
if 0 <= val < len(self.items):
self._index = val
def __call__(self, fn):
@wraps(fn)
def wrapper(a):
self.add(a)
return fn(a)
return wrapper