capturer-ng 4.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- capturer/__init__.py +719 -0
- capturer/tests.py +198 -0
- capturer_ng-4.0.dist-info/METADATA +271 -0
- capturer_ng-4.0.dist-info/RECORD +6 -0
- capturer_ng-4.0.dist-info/WHEEL +4 -0
- capturer_ng-4.0.dist-info/licenses/LICENSE.txt +20 -0
capturer/__init__.py
ADDED
|
@@ -0,0 +1,719 @@
|
|
|
1
|
+
# Easily capture stdout/stderr of the current process and subprocesses.
|
|
2
|
+
#
|
|
3
|
+
# Author: Peter Odding <peter@peterodding.com>
|
|
4
|
+
# Last Change: November 17, 2026
|
|
5
|
+
# URL: https://capturer.readthedocs.io
|
|
6
|
+
|
|
7
|
+
"""Easily capture stdout/stderr of the current process and subprocesses."""
|
|
8
|
+
|
|
9
|
+
# Standard library modules.
|
|
10
|
+
import multiprocessing
|
|
11
|
+
import os
|
|
12
|
+
import pty
|
|
13
|
+
import shutil
|
|
14
|
+
import signal
|
|
15
|
+
import sys
|
|
16
|
+
import tempfile
|
|
17
|
+
import time
|
|
18
|
+
|
|
19
|
+
# External dependencies.
|
|
20
|
+
from humanfriendly.deprecation import define_aliases
|
|
21
|
+
from humanfriendly.text import compact, dedent
|
|
22
|
+
from humanfriendly.terminal import clean_terminal_output
|
|
23
|
+
|
|
24
|
+
# Semi-standard module versioning.
|
|
25
|
+
__version__ = '4.0'
|
|
26
|
+
|
|
27
|
+
# Define aliases for backwards compatibility.
|
|
28
|
+
define_aliases(module_name=__name__, interpret_carriage_returns='humanfriendly.terminal.clean_terminal_output')
|
|
29
|
+
|
|
30
|
+
DEFAULT_TEXT_ENCODING = 'UTF-8'
|
|
31
|
+
"""
|
|
32
|
+
The name of the default character encoding used to convert captured output to
|
|
33
|
+
Unicode text (a string).
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
GRACEFUL_SHUTDOWN_SIGNAL = signal.SIGUSR1
|
|
37
|
+
"""
|
|
38
|
+
The number of the UNIX signal used to communicate graceful shutdown requests
|
|
39
|
+
from the main process to the output relay process (an integer). See also
|
|
40
|
+
:func:`~MultiProcessHelper.enable_graceful_shutdown()`.
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
TERMINATION_DELAY = 0.01
|
|
44
|
+
"""
|
|
45
|
+
The number of seconds to wait before terminating the output relay process (a
|
|
46
|
+
floating point number).
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
PARTIAL_DEFAULT = False
|
|
50
|
+
"""Whether partial reads are enabled or disabled by default (a boolean)."""
|
|
51
|
+
|
|
52
|
+
STDOUT_FD = 1
|
|
53
|
+
"""
|
|
54
|
+
The number of the file descriptor that refers to the standard output stream (an
|
|
55
|
+
integer).
|
|
56
|
+
"""
|
|
57
|
+
|
|
58
|
+
STDERR_FD = 2
|
|
59
|
+
"""
|
|
60
|
+
The number of the file descriptor that refers to the standard error stream (an
|
|
61
|
+
integer).
|
|
62
|
+
"""
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def enable_old_api():
|
|
66
|
+
"""
|
|
67
|
+
Enable backwards compatibility with the old API.
|
|
68
|
+
|
|
69
|
+
This function is called when the :mod:`capturer` module is imported. It
|
|
70
|
+
modifies the :class:`CaptureOutput` class to install method proxies for
|
|
71
|
+
:func:`~PseudoTerminal.get_handle()`, :func:`~PseudoTerminal.get_bytes()`,
|
|
72
|
+
:func:`~PseudoTerminal.get_lines()`, :func:`~PseudoTerminal.get_text()`,
|
|
73
|
+
:func:`~PseudoTerminal.save_to_handle()` and
|
|
74
|
+
:func:`~PseudoTerminal.save_to_path()`.
|
|
75
|
+
"""
|
|
76
|
+
for name in ('get_handle', 'get_bytes', 'get_lines', 'get_text', 'save_to_handle', 'save_to_path'):
|
|
77
|
+
setattr(CaptureOutput, name, create_proxy_method(name))
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def create_proxy_method(name):
|
|
81
|
+
"""
|
|
82
|
+
Create a proxy method for use by :func:`enable_old_api()`.
|
|
83
|
+
|
|
84
|
+
:param name: The name of the :class:`PseudoTerminal` method to call when
|
|
85
|
+
the proxy method is called.
|
|
86
|
+
:returns: A proxy method (a callable) to be installed on the
|
|
87
|
+
:class:`CaptureOutput` class.
|
|
88
|
+
"""
|
|
89
|
+
# Define the proxy method.
|
|
90
|
+
def proxy_method(self, *args, **kw):
|
|
91
|
+
if not hasattr(self, 'output'):
|
|
92
|
+
raise TypeError(compact("""
|
|
93
|
+
The old calling interface is only supported when
|
|
94
|
+
merged=True and start_capture() has been called!
|
|
95
|
+
"""))
|
|
96
|
+
real_method = getattr(self.output, name)
|
|
97
|
+
return real_method(*args, **kw)
|
|
98
|
+
# Get the docstring of the real method.
|
|
99
|
+
docstring = getattr(PseudoTerminal, name).__doc__
|
|
100
|
+
# Change the docstring to explain that this concerns a proxy method,
|
|
101
|
+
# but only when Sphinx is active (to avoid wasting time generating a
|
|
102
|
+
# docstring that no one is going to look at).
|
|
103
|
+
if 'sphinx' in sys.modules:
|
|
104
|
+
# Remove the signature from the docstring to make it possible to
|
|
105
|
+
# remove leading indentation from the remainder of the docstring.
|
|
106
|
+
lines = docstring.splitlines()
|
|
107
|
+
signature = lines.pop(0)
|
|
108
|
+
# Recompose the docstring from the signature, the remainder of the
|
|
109
|
+
# original docstring and the note about proxy methods.
|
|
110
|
+
docstring = '\n\n'.join([
|
|
111
|
+
signature,
|
|
112
|
+
dedent('\n'.join(lines)),
|
|
113
|
+
dedent("""
|
|
114
|
+
.. note:: This method is a proxy for the :func:`~PseudoTerminal.{name}()`
|
|
115
|
+
method of the :class:`PseudoTerminal` class. It requires
|
|
116
|
+
`merged` to be :data:`True` and it expects that
|
|
117
|
+
:func:`start_capture()` has been called. If this is not
|
|
118
|
+
the case then :exc:`~exceptions.TypeError` is raised.
|
|
119
|
+
""", name=name),
|
|
120
|
+
])
|
|
121
|
+
# Copy the (possible modified) docstring.
|
|
122
|
+
proxy_method.__doc__ = docstring
|
|
123
|
+
return proxy_method
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
class MultiProcessHelper(object):
|
|
127
|
+
|
|
128
|
+
"""
|
|
129
|
+
Helper to spawn and manipulate child processes using :mod:`multiprocessing`.
|
|
130
|
+
|
|
131
|
+
This class serves as a base class for :class:`CaptureOutput` and
|
|
132
|
+
:class:`PseudoTerminal` because both classes need the same child process
|
|
133
|
+
handling logic.
|
|
134
|
+
"""
|
|
135
|
+
|
|
136
|
+
def __init__(self):
|
|
137
|
+
"""Initialize a :class:`MultiProcessHelper` object."""
|
|
138
|
+
self.processes = []
|
|
139
|
+
try:
|
|
140
|
+
self.context = multiprocessing.get_context('fork')
|
|
141
|
+
except ValueError:
|
|
142
|
+
self.context = multiprocessing.get_context()
|
|
143
|
+
|
|
144
|
+
def start_child(self, target):
|
|
145
|
+
"""
|
|
146
|
+
Start a child process using :class:`multiprocessing.Process`.
|
|
147
|
+
|
|
148
|
+
:param target: The callable to run in the child process. Expected to
|
|
149
|
+
take a single argument which is a
|
|
150
|
+
:class:`multiprocessing.Event` to be set when the child
|
|
151
|
+
process has finished initialization.
|
|
152
|
+
"""
|
|
153
|
+
started_event = self.context.Event()
|
|
154
|
+
child_process = self.context.Process(target=target, args=(started_event,))
|
|
155
|
+
self.processes.append(child_process)
|
|
156
|
+
child_process.daemon = True
|
|
157
|
+
child_process.start()
|
|
158
|
+
started_event.wait()
|
|
159
|
+
|
|
160
|
+
def stop_children(self):
|
|
161
|
+
"""
|
|
162
|
+
Gracefully shut down all child processes.
|
|
163
|
+
|
|
164
|
+
Child processes are expected to call :func:`enable_graceful_shutdown()`
|
|
165
|
+
during initialization.
|
|
166
|
+
"""
|
|
167
|
+
while self.processes:
|
|
168
|
+
child_process = self.processes.pop()
|
|
169
|
+
if child_process.is_alive():
|
|
170
|
+
os.kill(child_process.pid, GRACEFUL_SHUTDOWN_SIGNAL)
|
|
171
|
+
child_process.join()
|
|
172
|
+
|
|
173
|
+
def wait_for_children(self):
|
|
174
|
+
"""Wait for all child processes to terminate."""
|
|
175
|
+
for child_process in self.processes:
|
|
176
|
+
child_process.join()
|
|
177
|
+
|
|
178
|
+
def enable_graceful_shutdown(self):
|
|
179
|
+
"""
|
|
180
|
+
Register a signal handler that converts :data:`GRACEFUL_SHUTDOWN_SIGNAL` to an exception.
|
|
181
|
+
|
|
182
|
+
Used by :func:`~PseudoTerminal.capture_loop()` to gracefully interrupt
|
|
183
|
+
the blocking :func:`os.read()` call when the capture loop needs to be
|
|
184
|
+
terminated (this is required for coverage collection).
|
|
185
|
+
"""
|
|
186
|
+
signal.signal(GRACEFUL_SHUTDOWN_SIGNAL, self.raise_shutdown_request)
|
|
187
|
+
|
|
188
|
+
def raise_shutdown_request(self, signum, frame):
|
|
189
|
+
"""Raise :exc:`ShutdownRequested` when :data:`GRACEFUL_SHUTDOWN_SIGNAL` is received."""
|
|
190
|
+
raise ShutdownRequested
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
class CaptureOutput(MultiProcessHelper):
|
|
194
|
+
|
|
195
|
+
"""Context manager to capture the standard output and error streams."""
|
|
196
|
+
|
|
197
|
+
def __init__(self, merged=True, encoding=DEFAULT_TEXT_ENCODING,
|
|
198
|
+
termination_delay=TERMINATION_DELAY, chunk_size=1024,
|
|
199
|
+
relay=True):
|
|
200
|
+
"""
|
|
201
|
+
Initialize a :class:`CaptureOutput` object.
|
|
202
|
+
|
|
203
|
+
:param merged: Whether to capture and relay the standard output and
|
|
204
|
+
standard error streams as one stream (a boolean,
|
|
205
|
+
defaults to :data:`True`). When this is :data:`False`
|
|
206
|
+
the ``stdout`` and ``stderr`` attributes of the
|
|
207
|
+
:class:`CaptureOutput` object are
|
|
208
|
+
:class:`PseudoTerminal` objects that can be used to
|
|
209
|
+
get at the output captured from each stream separately.
|
|
210
|
+
:param encoding: The name of the character encoding used to decode the
|
|
211
|
+
captured output (a string, defaults to
|
|
212
|
+
:data:`DEFAULT_TEXT_ENCODING`).
|
|
213
|
+
:param termination_delay: The number of seconds to wait before
|
|
214
|
+
terminating the output relay process (a
|
|
215
|
+
floating point number, defaults to
|
|
216
|
+
:data:`TERMINATION_DELAY`).
|
|
217
|
+
:param chunk_size: The maximum number of bytes to read from the
|
|
218
|
+
captured streams on each call to :func:`os.read()`
|
|
219
|
+
(an integer).
|
|
220
|
+
:param relay: If this is :data:`True` (the default) then captured
|
|
221
|
+
output is relayed to the terminal or parent process,
|
|
222
|
+
if it's :data:`False` the captured output is hidden
|
|
223
|
+
(swallowed).
|
|
224
|
+
"""
|
|
225
|
+
# Initialize the superclass.
|
|
226
|
+
super(CaptureOutput, self).__init__()
|
|
227
|
+
# Store constructor arguments.
|
|
228
|
+
self.chunk_size = chunk_size
|
|
229
|
+
self.encoding = encoding
|
|
230
|
+
self.merged = merged
|
|
231
|
+
self.relay = relay
|
|
232
|
+
self.termination_delay = termination_delay
|
|
233
|
+
# Initialize instance variables.
|
|
234
|
+
self.pseudo_terminals = []
|
|
235
|
+
self.streams = []
|
|
236
|
+
# Initialize stdout/stderr stream containers.
|
|
237
|
+
self.stdout_stream = self.initialize_stream(sys.stdout, STDOUT_FD)
|
|
238
|
+
self.stderr_stream = self.initialize_stream(sys.stderr, STDERR_FD)
|
|
239
|
+
|
|
240
|
+
def initialize_stream(self, file_obj, expected_fd):
|
|
241
|
+
"""
|
|
242
|
+
Initialize one or more :class:`Stream` objects to capture a standard stream.
|
|
243
|
+
|
|
244
|
+
:param file_obj: A file-like object with a ``fileno()`` method.
|
|
245
|
+
:param expected_fd: The expected file descriptor of the file-like object.
|
|
246
|
+
:returns: The :class:`Stream` connected to the file descriptor of the
|
|
247
|
+
file-like object.
|
|
248
|
+
|
|
249
|
+
By default this method just initializes a :class:`Stream` object
|
|
250
|
+
connected to the given file-like object and its underlying file
|
|
251
|
+
descriptor (a simple one-liner).
|
|
252
|
+
|
|
253
|
+
If however the file descriptor of the file-like object doesn't have the
|
|
254
|
+
expected value (``expected_fd``) two :class:`Stream` objects will be
|
|
255
|
+
created instead: One of the stream objects will be connected to the
|
|
256
|
+
file descriptor of the file-like object and the other stream object
|
|
257
|
+
will be connected to the file descriptor that was expected
|
|
258
|
+
(``expected_fd``).
|
|
259
|
+
|
|
260
|
+
This approach is intended to make sure that "nested" output capturing
|
|
261
|
+
works as expected: Output from the current Python process is captured
|
|
262
|
+
from the file descriptor of the file-like object while output from
|
|
263
|
+
subprocesses is captured from the file descriptor given by
|
|
264
|
+
``expected_fd`` (because the operating system defines special semantics
|
|
265
|
+
for the file descriptors with the numbers one and two that we can't
|
|
266
|
+
just ignore).
|
|
267
|
+
|
|
268
|
+
For more details refer to `issue 2 on GitHub
|
|
269
|
+
<https://github.com/xolox/python-capturer/issues/2>`_.
|
|
270
|
+
"""
|
|
271
|
+
real_fd = file_obj.fileno()
|
|
272
|
+
stream_obj = Stream(real_fd)
|
|
273
|
+
self.streams.append((expected_fd, stream_obj))
|
|
274
|
+
if real_fd != expected_fd:
|
|
275
|
+
self.streams.append((expected_fd, Stream(expected_fd)))
|
|
276
|
+
return stream_obj
|
|
277
|
+
|
|
278
|
+
def __enter__(self):
|
|
279
|
+
"""Automatically call :func:`start_capture()` when entering a :keyword:`with` block."""
|
|
280
|
+
self.start_capture()
|
|
281
|
+
return self
|
|
282
|
+
|
|
283
|
+
def __exit__(self, exc_type=None, exc_value=None, traceback=None):
|
|
284
|
+
"""Automatically call :func:`finish_capture()` when leaving a :keyword:`with` block."""
|
|
285
|
+
self.finish_capture()
|
|
286
|
+
|
|
287
|
+
@property
|
|
288
|
+
def is_capturing(self):
|
|
289
|
+
""":data:`True` if output is being captured, :data:`False` otherwise."""
|
|
290
|
+
return any(stream.is_redirected for kind, stream in self.streams)
|
|
291
|
+
|
|
292
|
+
def start_capture(self):
|
|
293
|
+
"""
|
|
294
|
+
Start capturing the standard output and error streams.
|
|
295
|
+
|
|
296
|
+
:raises: :exc:`~exceptions.TypeError` when output is already being
|
|
297
|
+
captured.
|
|
298
|
+
|
|
299
|
+
This method is called automatically when using the capture object as a
|
|
300
|
+
context manager. It's provided under a separate name in case someone
|
|
301
|
+
wants to extend :class:`CaptureOutput` and build their own context
|
|
302
|
+
manager on top of it.
|
|
303
|
+
"""
|
|
304
|
+
if self.is_capturing:
|
|
305
|
+
raise TypeError("Output capturing is already enabled!")
|
|
306
|
+
if self.merged:
|
|
307
|
+
# Capture (and most likely relay) stdout/stderr as one stream.
|
|
308
|
+
fd = self.stderr_stream.original_fd if self.relay else None
|
|
309
|
+
self.output = self.allocate_pty(relay_fd=fd)
|
|
310
|
+
for kind, stream in self.streams:
|
|
311
|
+
self.output.attach(stream)
|
|
312
|
+
else:
|
|
313
|
+
# Capture (and most likely relay) stdout/stderr as separate streams.
|
|
314
|
+
if self.relay:
|
|
315
|
+
# Start the subprocess to relay output.
|
|
316
|
+
self.output_queue = self.context.Queue()
|
|
317
|
+
self.start_child(self.merge_loop)
|
|
318
|
+
else:
|
|
319
|
+
# Disable relaying of output.
|
|
320
|
+
self.output_queue = None
|
|
321
|
+
self.stdout = self.allocate_pty(output_queue=self.output_queue, queue_token=STDOUT_FD)
|
|
322
|
+
self.stderr = self.allocate_pty(output_queue=self.output_queue, queue_token=STDERR_FD)
|
|
323
|
+
for kind, stream in self.streams:
|
|
324
|
+
if kind == STDOUT_FD:
|
|
325
|
+
self.stdout.attach(stream)
|
|
326
|
+
elif kind == STDERR_FD:
|
|
327
|
+
self.stderr.attach(stream)
|
|
328
|
+
else:
|
|
329
|
+
raise Exception("Programming error: Unrecognized stream type!")
|
|
330
|
+
# Start capturing and relaying of output (in one or two subprocesses).
|
|
331
|
+
for pseudo_terminal in self.pseudo_terminals:
|
|
332
|
+
pseudo_terminal.start_capture()
|
|
333
|
+
|
|
334
|
+
def finish_capture(self):
|
|
335
|
+
"""
|
|
336
|
+
Stop capturing the standard output and error streams.
|
|
337
|
+
|
|
338
|
+
This method is called automatically when using the capture object as a
|
|
339
|
+
context manager. It's provided under a separate name in case someone
|
|
340
|
+
wants to extend :class:`CaptureOutput` and build their own context
|
|
341
|
+
manager on top of it.
|
|
342
|
+
"""
|
|
343
|
+
for pseudo_terminal in self.pseudo_terminals:
|
|
344
|
+
pseudo_terminal.finish_capture()
|
|
345
|
+
self.wait_for_children()
|
|
346
|
+
|
|
347
|
+
def allocate_pty(self, relay_fd=None, output_queue=None, queue_token=None):
|
|
348
|
+
"""
|
|
349
|
+
Allocate a pseudo terminal.
|
|
350
|
+
|
|
351
|
+
Internal shortcut for :func:`start_capture()` to allocate multiple
|
|
352
|
+
pseudo terminals without code duplication.
|
|
353
|
+
"""
|
|
354
|
+
obj = PseudoTerminal(
|
|
355
|
+
self.encoding, self.termination_delay, self.chunk_size,
|
|
356
|
+
relay_fd=relay_fd, output_queue=output_queue,
|
|
357
|
+
queue_token=queue_token,
|
|
358
|
+
)
|
|
359
|
+
self.pseudo_terminals.append(obj)
|
|
360
|
+
return obj
|
|
361
|
+
|
|
362
|
+
def merge_loop(self, started_event):
|
|
363
|
+
"""
|
|
364
|
+
Merge and relay output in a child process.
|
|
365
|
+
|
|
366
|
+
This internal method is used when standard output and standard error
|
|
367
|
+
are being captured separately. It's responsible for emitting each
|
|
368
|
+
captured line on the appropriate stream without interleaving text
|
|
369
|
+
within lines.
|
|
370
|
+
"""
|
|
371
|
+
buffers = {
|
|
372
|
+
STDOUT_FD: OutputBuffer(self.stdout_stream.original_fd),
|
|
373
|
+
STDERR_FD: OutputBuffer(self.stderr_stream.original_fd),
|
|
374
|
+
}
|
|
375
|
+
started_event.set()
|
|
376
|
+
while buffers:
|
|
377
|
+
captured_from, output = self.output_queue.get()
|
|
378
|
+
if output:
|
|
379
|
+
buffers[captured_from].add(output)
|
|
380
|
+
else:
|
|
381
|
+
buffers[captured_from].flush()
|
|
382
|
+
buffers.pop(captured_from)
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
class OutputBuffer(object):
|
|
386
|
+
|
|
387
|
+
"""
|
|
388
|
+
Helper for :func:`CaptureOutput.merge_loop()`.
|
|
389
|
+
|
|
390
|
+
Buffers captured output and flushes to the appropriate stream after each
|
|
391
|
+
line break.
|
|
392
|
+
"""
|
|
393
|
+
|
|
394
|
+
def __init__(self, fd):
|
|
395
|
+
"""
|
|
396
|
+
Initialize an :class:`OutputBuffer` object.
|
|
397
|
+
|
|
398
|
+
:param fd: The number of the file descriptor where output should be
|
|
399
|
+
flushed (an integer).
|
|
400
|
+
"""
|
|
401
|
+
self.fd = fd
|
|
402
|
+
self.buffer = b''
|
|
403
|
+
|
|
404
|
+
def add(self, output):
|
|
405
|
+
"""
|
|
406
|
+
Add output to the buffer and flush appropriately.
|
|
407
|
+
|
|
408
|
+
:param output: The output to add to the buffer (a string).
|
|
409
|
+
"""
|
|
410
|
+
self.buffer += output
|
|
411
|
+
if b'\n' in self.buffer:
|
|
412
|
+
before, _, self.buffer = self.buffer.rpartition(b'\n')
|
|
413
|
+
os.write(self.fd, before + b'\n')
|
|
414
|
+
|
|
415
|
+
def flush(self):
|
|
416
|
+
"""Flush any remaining buffered output to the stream."""
|
|
417
|
+
os.write(self.fd, self.buffer)
|
|
418
|
+
self.buffer = b''
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
class PseudoTerminal(MultiProcessHelper):
|
|
422
|
+
|
|
423
|
+
"""
|
|
424
|
+
Helper for :class:`CaptureOutput`.
|
|
425
|
+
|
|
426
|
+
Manages capturing of output and exposing the captured output.
|
|
427
|
+
"""
|
|
428
|
+
|
|
429
|
+
def __init__(self, encoding, termination_delay, chunk_size, relay_fd, output_queue, queue_token):
|
|
430
|
+
"""
|
|
431
|
+
Initialize a :class:`PseudoTerminal` object.
|
|
432
|
+
|
|
433
|
+
:param encoding: The name of the character encoding used to decode the
|
|
434
|
+
captured output (a string, defaults to
|
|
435
|
+
:data:`DEFAULT_TEXT_ENCODING`).
|
|
436
|
+
:param termination_delay: The number of seconds to wait before
|
|
437
|
+
terminating the output relay process (a
|
|
438
|
+
floating point number, defaults to
|
|
439
|
+
:data:`TERMINATION_DELAY`).
|
|
440
|
+
:param chunk_size: The maximum number of bytes to read from the
|
|
441
|
+
captured stream(s) on each call to :func:`os.read()`
|
|
442
|
+
(an integer).
|
|
443
|
+
:param relay_fd: The number of the file descriptor where captured
|
|
444
|
+
output should be relayed to (an integer or
|
|
445
|
+
:data:`None` if ``output_queue`` and ``queue_token``
|
|
446
|
+
are given).
|
|
447
|
+
:param output_queue: The multiprocessing queue where captured output
|
|
448
|
+
chunks should be written to (a
|
|
449
|
+
:class:`multiprocessing.Queue` object or
|
|
450
|
+
:data:`None` if ``relay_fd`` is given).
|
|
451
|
+
:param queue_token: A unique identifier added to each output chunk
|
|
452
|
+
written to the queue (any value or :data:`None` if
|
|
453
|
+
``relay_fd`` is given).
|
|
454
|
+
"""
|
|
455
|
+
# Initialize the superclass.
|
|
456
|
+
super(PseudoTerminal, self).__init__()
|
|
457
|
+
# Store constructor arguments.
|
|
458
|
+
self.encoding = encoding
|
|
459
|
+
self.termination_delay = termination_delay
|
|
460
|
+
self.chunk_size = chunk_size
|
|
461
|
+
self.relay_fd = relay_fd
|
|
462
|
+
self.output_queue = output_queue
|
|
463
|
+
self.queue_token = queue_token
|
|
464
|
+
# Initialize instance variables.
|
|
465
|
+
self.streams = []
|
|
466
|
+
# Allocate a pseudo terminal so we can fake subprocesses into
|
|
467
|
+
# thinking that they are connected to a real terminal (this will
|
|
468
|
+
# trigger them to use e.g. ANSI escape sequences).
|
|
469
|
+
self.master_fd, self.slave_fd = pty.openpty()
|
|
470
|
+
# Create a temporary file in which we'll store the output received on
|
|
471
|
+
# the master end of the pseudo terminal.
|
|
472
|
+
self.output_fd, output_file = tempfile.mkstemp()
|
|
473
|
+
self.output_handle = open(output_file, 'rb')
|
|
474
|
+
# Unlink the temporary file because we have a readable file descriptor
|
|
475
|
+
# and a writable file descriptor and that's all we need! If this
|
|
476
|
+
# surprises you I suggest you investigate why unlink() was named the
|
|
477
|
+
# way it was in UNIX :-).
|
|
478
|
+
os.unlink(output_file)
|
|
479
|
+
|
|
480
|
+
def attach(self, stream):
|
|
481
|
+
"""
|
|
482
|
+
Attach a stream to the pseudo terminal.
|
|
483
|
+
|
|
484
|
+
:param stream: A :class:`Stream` object.
|
|
485
|
+
"""
|
|
486
|
+
stream.redirect(self.slave_fd)
|
|
487
|
+
self.streams.append(stream)
|
|
488
|
+
|
|
489
|
+
def start_capture(self):
|
|
490
|
+
"""Start the child process(es) responsible for capturing and relaying output."""
|
|
491
|
+
self.start_child(self.capture_loop)
|
|
492
|
+
|
|
493
|
+
def finish_capture(self):
|
|
494
|
+
"""Stop the process of capturing output and destroy the pseudo terminal."""
|
|
495
|
+
time.sleep(self.termination_delay)
|
|
496
|
+
self.stop_children()
|
|
497
|
+
self.close_pseudo_terminal()
|
|
498
|
+
self.restore_streams()
|
|
499
|
+
|
|
500
|
+
def close_pseudo_terminal(self):
|
|
501
|
+
"""Close the pseudo terminal's master/slave file descriptors."""
|
|
502
|
+
for name in ('master_fd', 'slave_fd'):
|
|
503
|
+
fd = getattr(self, name)
|
|
504
|
+
if fd is not None:
|
|
505
|
+
os.close(fd)
|
|
506
|
+
setattr(self, name, None)
|
|
507
|
+
|
|
508
|
+
def restore_streams(self):
|
|
509
|
+
"""Restore the stream(s) attached to the pseudo terminal."""
|
|
510
|
+
for stream in self.streams:
|
|
511
|
+
stream.restore()
|
|
512
|
+
|
|
513
|
+
# The CaptureOutput class contains proxy methods for the get_handle(),
|
|
514
|
+
# get_bytes(), get_lines(), get_text(), save_to_handle() and save_to_path()
|
|
515
|
+
# methods defined below. By default Sphinx generates method signatures of
|
|
516
|
+
# the form f(proxy, *args, **kw) for these proxy methods, with the result
|
|
517
|
+
# that the online documentation is rather confusing. As a workaround I've
|
|
518
|
+
# included explicit method signatures in the first line of each of the
|
|
519
|
+
# docstrings. This works because of the following Sphinx option:
|
|
520
|
+
# http://www.sphinx-doc.org/en/latest/ext/autodoc.html#confval-autodoc_docstring_signature
|
|
521
|
+
|
|
522
|
+
def get_handle(self, partial=PARTIAL_DEFAULT):
|
|
523
|
+
"""get_handle(partial=False)
|
|
524
|
+
Get the captured output as a Python file object.
|
|
525
|
+
|
|
526
|
+
:param partial: If :data:`True` (*not the default*) the partial output
|
|
527
|
+
captured so far is returned, otherwise (*so by
|
|
528
|
+
default*) the relay process is terminated and output
|
|
529
|
+
capturing is disabled before returning the captured
|
|
530
|
+
output (the default is intended to protect unsuspecting
|
|
531
|
+
users against partial reads).
|
|
532
|
+
:returns: The captured output as a Python file object. The file
|
|
533
|
+
object's current position is reset to zero before this
|
|
534
|
+
function returns.
|
|
535
|
+
|
|
536
|
+
This method is useful when you're dealing with arbitrary amounts of
|
|
537
|
+
captured data that you don't want to load into memory just so you can
|
|
538
|
+
save it to a file again. In fact, in that case you might want to take a
|
|
539
|
+
look at :func:`save_to_path()` and/or :func:`save_to_handle()` :-).
|
|
540
|
+
|
|
541
|
+
.. warning:: Two caveats about the use of this method:
|
|
542
|
+
|
|
543
|
+
1. If partial is :data:`True` (not the default) the output
|
|
544
|
+
can end in a partial line, possibly in the middle of an
|
|
545
|
+
ANSI escape sequence or a multi byte character.
|
|
546
|
+
|
|
547
|
+
2. If you close this file handle you just lost your last
|
|
548
|
+
chance to get at the captured output! (calling this
|
|
549
|
+
method again will not give you a new file handle)
|
|
550
|
+
"""
|
|
551
|
+
if not partial:
|
|
552
|
+
self.finish_capture()
|
|
553
|
+
self.output_handle.seek(0)
|
|
554
|
+
return self.output_handle
|
|
555
|
+
|
|
556
|
+
def get_bytes(self, partial=PARTIAL_DEFAULT):
|
|
557
|
+
"""get_bytes(partial=False)
|
|
558
|
+
Get the captured output as binary data.
|
|
559
|
+
|
|
560
|
+
:param partial: Refer to :func:`get_handle()` for details.
|
|
561
|
+
:returns: The captured output as a binary string.
|
|
562
|
+
"""
|
|
563
|
+
return self.get_handle(partial).read()
|
|
564
|
+
|
|
565
|
+
def get_lines(self, interpreted=True, partial=PARTIAL_DEFAULT):
|
|
566
|
+
"""get_lines(interpreted=True, partial=False)
|
|
567
|
+
Get the captured output split into lines.
|
|
568
|
+
|
|
569
|
+
:param interpreted: If :data:`True` (the default) captured output is
|
|
570
|
+
processed using :func:`.clean_terminal_output()`.
|
|
571
|
+
:param partial: Refer to :func:`get_handle()` for details.
|
|
572
|
+
:returns: The captured output as a list of Unicode strings.
|
|
573
|
+
|
|
574
|
+
.. warning:: If partial is :data:`True` (not the default) the output
|
|
575
|
+
can end in a partial line, possibly in the middle of a
|
|
576
|
+
multi byte character (this may cause decoding errors).
|
|
577
|
+
"""
|
|
578
|
+
output = self.get_bytes(partial)
|
|
579
|
+
output = output.decode(self.encoding)
|
|
580
|
+
if interpreted:
|
|
581
|
+
return clean_terminal_output(output)
|
|
582
|
+
else:
|
|
583
|
+
return output.splitlines()
|
|
584
|
+
|
|
585
|
+
def get_text(self, interpreted=True, partial=PARTIAL_DEFAULT):
|
|
586
|
+
"""get_text(interpreted=True, partial=False)
|
|
587
|
+
Get the captured output as a single string.
|
|
588
|
+
|
|
589
|
+
:param interpreted: If :data:`True` (the default) captured output is
|
|
590
|
+
processed using :func:`clean_terminal_output()`.
|
|
591
|
+
:param partial: Refer to :func:`get_handle()` for details.
|
|
592
|
+
:returns: The captured output as a Unicode string.
|
|
593
|
+
|
|
594
|
+
.. warning:: If partial is :data:`True` (not the default) the output
|
|
595
|
+
can end in a partial line, possibly in the middle of a
|
|
596
|
+
multi byte character (this may cause decoding errors).
|
|
597
|
+
"""
|
|
598
|
+
output = self.get_bytes(partial)
|
|
599
|
+
output = output.decode(self.encoding)
|
|
600
|
+
if interpreted:
|
|
601
|
+
output = u'\n'.join(clean_terminal_output(output))
|
|
602
|
+
return output
|
|
603
|
+
|
|
604
|
+
def save_to_handle(self, handle, partial=PARTIAL_DEFAULT):
|
|
605
|
+
"""save_to_handle(handle, partial=False)
|
|
606
|
+
Save the captured output to an open file handle.
|
|
607
|
+
|
|
608
|
+
:param handle: A writable file-like object.
|
|
609
|
+
:param partial: Refer to :func:`get_handle()` for details.
|
|
610
|
+
"""
|
|
611
|
+
shutil.copyfileobj(self.get_handle(partial), handle)
|
|
612
|
+
|
|
613
|
+
def save_to_path(self, filename, partial=PARTIAL_DEFAULT):
|
|
614
|
+
"""save_to_path(filename, partial=False)
|
|
615
|
+
Save the captured output to a file.
|
|
616
|
+
|
|
617
|
+
:param filename: The pathname of the file where the captured output
|
|
618
|
+
should be written to (a string).
|
|
619
|
+
:param partial: Refer to :func:`get_handle()` for details.
|
|
620
|
+
"""
|
|
621
|
+
with open(filename, 'wb') as handle:
|
|
622
|
+
self.save_to_handle(handle, partial)
|
|
623
|
+
|
|
624
|
+
def capture_loop(self, started_event):
|
|
625
|
+
"""
|
|
626
|
+
Continuously read from the master end of the pseudo terminal and relay the output.
|
|
627
|
+
|
|
628
|
+
This function is run in the background by :func:`start_capture()`
|
|
629
|
+
using the :mod:`multiprocessing` module. It's role is to read output
|
|
630
|
+
emitted on the master end of the pseudo terminal and relay this output
|
|
631
|
+
to the real terminal (so the operator can see what's happening in real
|
|
632
|
+
time) as well as a temporary file (for additional processing by the
|
|
633
|
+
caller).
|
|
634
|
+
"""
|
|
635
|
+
self.enable_graceful_shutdown()
|
|
636
|
+
started_event.set()
|
|
637
|
+
try:
|
|
638
|
+
while True:
|
|
639
|
+
# Read from the master end of the pseudo terminal.
|
|
640
|
+
output = os.read(self.master_fd, self.chunk_size)
|
|
641
|
+
if output:
|
|
642
|
+
# Store the output in the temporary file.
|
|
643
|
+
os.write(self.output_fd, output)
|
|
644
|
+
# Relay the output to the real terminal?
|
|
645
|
+
if self.relay_fd is not None:
|
|
646
|
+
os.write(self.relay_fd, output)
|
|
647
|
+
# Relay the output to the master process?
|
|
648
|
+
if self.output_queue is not None:
|
|
649
|
+
self.output_queue.put((self.queue_token, output))
|
|
650
|
+
else:
|
|
651
|
+
# Relinquish our time slice, or in other words: try to be
|
|
652
|
+
# friendly to other processes when os.read() calls don't
|
|
653
|
+
# block. Just for the record, all of my experiments have
|
|
654
|
+
# shown that os.read() on the master file descriptor
|
|
655
|
+
# returned by pty.openpty() does in fact block.
|
|
656
|
+
time.sleep(0)
|
|
657
|
+
except ShutdownRequested:
|
|
658
|
+
# Let the master process know that we're shutting down.
|
|
659
|
+
if self.output_queue is not None:
|
|
660
|
+
self.output_queue.put((self.queue_token, ''))
|
|
661
|
+
|
|
662
|
+
|
|
663
|
+
class Stream(object):
|
|
664
|
+
|
|
665
|
+
"""
|
|
666
|
+
Container for standard stream redirection logic.
|
|
667
|
+
|
|
668
|
+
Used by :class:`CaptureOutput` to temporarily redirect the standard output
|
|
669
|
+
and standard error streams.
|
|
670
|
+
|
|
671
|
+
.. attribute:: is_redirected
|
|
672
|
+
|
|
673
|
+
:data:`True` once :func:`redirect()` has been called, :data:`False` when
|
|
674
|
+
:func:`redirect()` hasn't been called yet or :func:`restore()` has since
|
|
675
|
+
been called.
|
|
676
|
+
"""
|
|
677
|
+
|
|
678
|
+
def __init__(self, fd):
|
|
679
|
+
"""
|
|
680
|
+
Initialize a :class:`Stream` object.
|
|
681
|
+
|
|
682
|
+
:param fd: The file descriptor to be redirected (an integer).
|
|
683
|
+
"""
|
|
684
|
+
self.fd = fd
|
|
685
|
+
self.original_fd = os.dup(self.fd)
|
|
686
|
+
self.is_redirected = False
|
|
687
|
+
|
|
688
|
+
def redirect(self, target_fd):
|
|
689
|
+
"""
|
|
690
|
+
Redirect output written to the file descriptor to another file descriptor.
|
|
691
|
+
|
|
692
|
+
:param target_fd: The file descriptor that should receive the output
|
|
693
|
+
written to the file descriptor given to the
|
|
694
|
+
:class:`Stream` constructor (an integer).
|
|
695
|
+
:raises: :exc:`~exceptions.TypeError` when the file descriptor is
|
|
696
|
+
already being redirected.
|
|
697
|
+
"""
|
|
698
|
+
if self.is_redirected:
|
|
699
|
+
msg = "File descriptor %s is already being redirected!"
|
|
700
|
+
raise TypeError(msg % self.fd)
|
|
701
|
+
os.dup2(target_fd, self.fd)
|
|
702
|
+
self.is_redirected = True
|
|
703
|
+
|
|
704
|
+
def restore(self):
|
|
705
|
+
"""Stop redirecting output written to the file descriptor."""
|
|
706
|
+
if self.is_redirected:
|
|
707
|
+
os.dup2(self.original_fd, self.fd)
|
|
708
|
+
self.is_redirected = False
|
|
709
|
+
|
|
710
|
+
|
|
711
|
+
class ShutdownRequested(Exception):
|
|
712
|
+
|
|
713
|
+
"""
|
|
714
|
+
Raised by :func:`~MultiProcessHelper.raise_shutdown_request()` to signal
|
|
715
|
+
graceful termination requests (in :func:`~PseudoTerminal.capture_loop()`).
|
|
716
|
+
"""
|
|
717
|
+
|
|
718
|
+
|
|
719
|
+
enable_old_api()
|
capturer/tests.py
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
# Easily capture stdout/stderr of the current process and subprocesses.
|
|
2
|
+
#
|
|
3
|
+
# Author: Peter Odding <peter@peterodding.com>
|
|
4
|
+
# Last Change: March 7, 2020
|
|
5
|
+
# URL: https://capturer.readthedocs.io
|
|
6
|
+
|
|
7
|
+
"""Test suite for the `capturer` package."""
|
|
8
|
+
|
|
9
|
+
# Standard library modules.
|
|
10
|
+
import os
|
|
11
|
+
import subprocess
|
|
12
|
+
import sys
|
|
13
|
+
import tempfile
|
|
14
|
+
import unittest
|
|
15
|
+
|
|
16
|
+
# External dependencies.
|
|
17
|
+
from humanfriendly.terminal import clean_terminal_output
|
|
18
|
+
from humanfriendly.testing import TestCase, random_string, retry
|
|
19
|
+
|
|
20
|
+
# The module we're testing.
|
|
21
|
+
from capturer import CaptureOutput, Stream
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class CapturerTestCase(TestCase):
|
|
25
|
+
|
|
26
|
+
"""Container for the `capturer` test suite."""
|
|
27
|
+
|
|
28
|
+
def test_carriage_return_interpretation(self):
|
|
29
|
+
"""Sanity check the results of clean_terminal_output()."""
|
|
30
|
+
# Simple output should pass through unharmed.
|
|
31
|
+
assert clean_terminal_output('foo') == ['foo']
|
|
32
|
+
# Simple output should pass through unharmed.
|
|
33
|
+
assert clean_terminal_output('foo\nbar') == ['foo', 'bar']
|
|
34
|
+
# Carriage returns and preceding substrings should be stripped.
|
|
35
|
+
assert clean_terminal_output('foo\rbar\nbaz') == ['bar', 'baz']
|
|
36
|
+
# Trailing empty lines should be stripped.
|
|
37
|
+
assert clean_terminal_output('foo\nbar\nbaz\n\n\n') == ['foo', 'bar', 'baz']
|
|
38
|
+
|
|
39
|
+
def test_error_handling(self):
|
|
40
|
+
"""Test error handling code paths."""
|
|
41
|
+
# Nested CaptureOutput.start_capture() calls should raise an exception.
|
|
42
|
+
capturer = CaptureOutput()
|
|
43
|
+
capturer.start_capture()
|
|
44
|
+
try:
|
|
45
|
+
self.assertRaises(TypeError, capturer.start_capture)
|
|
46
|
+
finally:
|
|
47
|
+
# Make sure not to start swallowing output here ;-).
|
|
48
|
+
capturer.finish_capture()
|
|
49
|
+
# Nested Stream.redirect() calls should raise an exception.
|
|
50
|
+
stream = Stream(sys.stdout.fileno())
|
|
51
|
+
stream.redirect(sys.stderr.fileno())
|
|
52
|
+
self.assertRaises(TypeError, stream.redirect, sys.stderr.fileno())
|
|
53
|
+
|
|
54
|
+
def test_stdout_capture_same_process(self):
|
|
55
|
+
"""Test standard output capturing from the same process."""
|
|
56
|
+
expected_stdout = random_string()
|
|
57
|
+
with CaptureOutput() as capturer:
|
|
58
|
+
print(expected_stdout)
|
|
59
|
+
assert expected_stdout in capturer.get_lines()
|
|
60
|
+
|
|
61
|
+
def test_stderr_capture_same_process(self):
|
|
62
|
+
"""Test standard error capturing from the same process."""
|
|
63
|
+
expected_stderr = random_string()
|
|
64
|
+
with CaptureOutput() as capturer:
|
|
65
|
+
sys.stderr.write(expected_stderr + "\n")
|
|
66
|
+
assert expected_stderr in capturer.get_lines()
|
|
67
|
+
|
|
68
|
+
def test_combined_capture_same_process(self):
|
|
69
|
+
"""Test combined standard output and error capturing from the same process."""
|
|
70
|
+
expected_stdout = random_string()
|
|
71
|
+
expected_stderr = random_string()
|
|
72
|
+
with CaptureOutput() as capturer:
|
|
73
|
+
sys.stdout.write(expected_stdout + "\n")
|
|
74
|
+
sys.stderr.write(expected_stderr + "\n")
|
|
75
|
+
assert expected_stdout in capturer.get_lines()
|
|
76
|
+
assert expected_stderr in capturer.get_lines()
|
|
77
|
+
|
|
78
|
+
def test_stdout_capture_subprocess(self):
|
|
79
|
+
"""Test standard output capturing from subprocesses."""
|
|
80
|
+
expected_stdout = random_string()
|
|
81
|
+
with CaptureOutput() as capturer:
|
|
82
|
+
subprocess.call([
|
|
83
|
+
sys.executable,
|
|
84
|
+
'-c',
|
|
85
|
+
';'.join([
|
|
86
|
+
'import sys',
|
|
87
|
+
'sys.stdout.write(%r)' % (expected_stdout + '\n'),
|
|
88
|
+
]),
|
|
89
|
+
])
|
|
90
|
+
assert expected_stdout in capturer.get_lines()
|
|
91
|
+
|
|
92
|
+
def test_stderr_capture_subprocess(self):
|
|
93
|
+
"""Test standard error capturing from subprocesses."""
|
|
94
|
+
expected_stderr = random_string()
|
|
95
|
+
with CaptureOutput() as capturer:
|
|
96
|
+
subprocess.call([
|
|
97
|
+
sys.executable,
|
|
98
|
+
'-c',
|
|
99
|
+
';'.join([
|
|
100
|
+
'import sys',
|
|
101
|
+
'sys.stderr.write(%r)' % (expected_stderr + '\n'),
|
|
102
|
+
]),
|
|
103
|
+
])
|
|
104
|
+
assert expected_stderr in capturer.get_lines()
|
|
105
|
+
|
|
106
|
+
def test_combined_capture_subprocess(self):
|
|
107
|
+
"""Test combined standard output and error capturing from subprocesses."""
|
|
108
|
+
expected_stdout = random_string()
|
|
109
|
+
expected_stderr = random_string()
|
|
110
|
+
with CaptureOutput() as capturer:
|
|
111
|
+
subprocess.call([
|
|
112
|
+
sys.executable,
|
|
113
|
+
'-c',
|
|
114
|
+
';'.join([
|
|
115
|
+
'import sys',
|
|
116
|
+
'sys.stdout.write(%r)' % (expected_stdout + '\n'),
|
|
117
|
+
'sys.stderr.write(%r)' % (expected_stderr + '\n'),
|
|
118
|
+
]),
|
|
119
|
+
])
|
|
120
|
+
assert expected_stdout in capturer.get_lines()
|
|
121
|
+
assert expected_stderr in capturer.get_lines()
|
|
122
|
+
|
|
123
|
+
def test_combined_current_and_subprocess(self):
|
|
124
|
+
"""Test combined standard output and error capturing from the same process and subprocesses."""
|
|
125
|
+
# Some unique strings that are not substrings of each other.
|
|
126
|
+
cur_stdout_1 = "Some output from Python's print statement"
|
|
127
|
+
cur_stdout_2 = "Output from Python's sys.stdout.write() method"
|
|
128
|
+
cur_stdout_3 = "More output from Python's print statement"
|
|
129
|
+
cur_stderr = "Output from Python's sys.stderr.write() method"
|
|
130
|
+
sub_stderr = "Output from subprocess stderr stream"
|
|
131
|
+
sub_stdout = "Output from subprocess stdout stream"
|
|
132
|
+
with CaptureOutput() as capturer:
|
|
133
|
+
# Emit multiple lines on both streams from current process and subprocess.
|
|
134
|
+
print(cur_stdout_1)
|
|
135
|
+
sys.stderr.write("%s\n" % cur_stderr)
|
|
136
|
+
subprocess.call(["sh", "-c", "echo %s 1>&2" % sub_stderr])
|
|
137
|
+
subprocess.call(["echo", sub_stdout])
|
|
138
|
+
sys.stdout.write("%s\n" % cur_stdout_2)
|
|
139
|
+
print(cur_stdout_3)
|
|
140
|
+
# Verify that all of the expected lines were captured.
|
|
141
|
+
assert all(line in capturer.get_lines() for line in (
|
|
142
|
+
cur_stdout_1, cur_stderr, sub_stderr,
|
|
143
|
+
sub_stdout, cur_stdout_2, cur_stdout_3,
|
|
144
|
+
))
|
|
145
|
+
|
|
146
|
+
def test_partial_read(self):
|
|
147
|
+
"""Test that partial reading works as expected."""
|
|
148
|
+
# This test method uses retry logic because `partial=True' makes these
|
|
149
|
+
# tests prone to race conditions (this is the whole reason why
|
|
150
|
+
# `partial=False' by default :-).
|
|
151
|
+
initial_part = random_string()
|
|
152
|
+
later_part = random_string()
|
|
153
|
+
with CaptureOutput() as capturer:
|
|
154
|
+
sys.stderr.write("%s\n" % initial_part)
|
|
155
|
+
retry(lambda: initial_part in capturer.get_lines(partial=True))
|
|
156
|
+
sys.stderr.write("%s\n" % later_part)
|
|
157
|
+
retry(lambda: later_part in capturer.get_lines(partial=True))
|
|
158
|
+
|
|
159
|
+
def test_non_interpreted_lines_capture(self):
|
|
160
|
+
"""Test that interpretation of special characters can be disabled."""
|
|
161
|
+
expected_output = random_string()
|
|
162
|
+
with CaptureOutput() as capturer:
|
|
163
|
+
print(expected_output)
|
|
164
|
+
assert expected_output in capturer.get_lines(interpreted=False)
|
|
165
|
+
|
|
166
|
+
def test_text_capture(self):
|
|
167
|
+
"""Test that capturing of all output as a single string is supported."""
|
|
168
|
+
expected_output = random_string()
|
|
169
|
+
with CaptureOutput() as capturer:
|
|
170
|
+
print(expected_output)
|
|
171
|
+
assert expected_output in capturer.get_text()
|
|
172
|
+
|
|
173
|
+
def test_save_to_path(self):
|
|
174
|
+
"""Test that captured output can be stored in a file."""
|
|
175
|
+
expected_output = random_string()
|
|
176
|
+
with CaptureOutput() as capturer:
|
|
177
|
+
print(expected_output)
|
|
178
|
+
fd, temporary_file = tempfile.mkstemp()
|
|
179
|
+
try:
|
|
180
|
+
capturer.save_to_path(temporary_file)
|
|
181
|
+
with open(temporary_file, 'r') as handle:
|
|
182
|
+
assert expected_output in handle.read()
|
|
183
|
+
finally:
|
|
184
|
+
os.unlink(temporary_file)
|
|
185
|
+
|
|
186
|
+
def test_unmerged_capture(self):
|
|
187
|
+
"""Test that standard output and error can be captured separately."""
|
|
188
|
+
expected_stdout = random_string()
|
|
189
|
+
expected_stderr = random_string()
|
|
190
|
+
with CaptureOutput(merged=False) as capturer:
|
|
191
|
+
sys.stdout.write(expected_stdout + "\n")
|
|
192
|
+
sys.stderr.write(expected_stderr + "\n")
|
|
193
|
+
assert expected_stdout in capturer.stdout.get_lines()
|
|
194
|
+
assert expected_stderr in capturer.stderr.get_lines()
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
if __name__ == '__main__':
|
|
198
|
+
unittest.main()
|
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: capturer-ng
|
|
3
|
+
Version: 4.0
|
|
4
|
+
Summary: Easily capture stdout/stderr of the current process and subprocesses
|
|
5
|
+
Project-URL: Homepage, https://github.com/marco8154/python-capturer-ng
|
|
6
|
+
Project-URL: Documentation, https://capturer.readthedocs.io
|
|
7
|
+
Project-URL: Changelog, https://github.com/marco8154/python-capturer-ng/blob/master/CHANGELOG.rst
|
|
8
|
+
Project-URL: Original project, https://github.com/xolox/python-capturer
|
|
9
|
+
Author-email: Peter Odding <peter@peterodding.com>
|
|
10
|
+
Maintainer: marco8154
|
|
11
|
+
License-Expression: MIT
|
|
12
|
+
License-File: LICENSE.txt
|
|
13
|
+
Classifier: Development Status :: 4 - Beta
|
|
14
|
+
Classifier: Environment :: Console
|
|
15
|
+
Classifier: Intended Audience :: Developers
|
|
16
|
+
Classifier: Intended Audience :: Information Technology
|
|
17
|
+
Classifier: Intended Audience :: System Administrators
|
|
18
|
+
Classifier: Natural Language :: English
|
|
19
|
+
Classifier: Operating System :: POSIX
|
|
20
|
+
Classifier: Operating System :: Unix
|
|
21
|
+
Classifier: Programming Language :: Python
|
|
22
|
+
Classifier: Programming Language :: Python :: 3
|
|
23
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
24
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
25
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
26
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
27
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
28
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
29
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
30
|
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
|
31
|
+
Classifier: Topic :: Communications
|
|
32
|
+
Classifier: Topic :: Scientific/Engineering :: Human Machine Interfaces
|
|
33
|
+
Classifier: Topic :: Software Development
|
|
34
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
35
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
36
|
+
Classifier: Topic :: Software Development :: User Interfaces
|
|
37
|
+
Classifier: Topic :: System :: Shells
|
|
38
|
+
Classifier: Topic :: System :: System Shells
|
|
39
|
+
Classifier: Topic :: System :: Systems Administration
|
|
40
|
+
Classifier: Topic :: Terminals
|
|
41
|
+
Classifier: Topic :: Text Processing :: General
|
|
42
|
+
Requires-Python: >=3.10
|
|
43
|
+
Requires-Dist: humanfriendly-ng
|
|
44
|
+
Description-Content-Type: text/x-rst
|
|
45
|
+
|
|
46
|
+
capturer: Easily capture stdout/stderr of the current process and subprocesses
|
|
47
|
+
==============================================================================
|
|
48
|
+
|
|
49
|
+
.. image:: https://github.com/marco8154/python-capturer-ng/actions/workflows/test.yml/badge.svg?branch=master
|
|
50
|
+
:target: https://github.com/marco8154/python-capturer-ng/actions
|
|
51
|
+
|
|
52
|
+
The capturer package makes it easy to capture the stdout_ and stderr_ streams
|
|
53
|
+
of the current process *and subprocesses*. Output can be relayed to the
|
|
54
|
+
terminal in real time but is also available to the Python program for
|
|
55
|
+
additional processing. It's currently tested on Python 3.10 and newer. It's
|
|
56
|
+
tested on Linux and Mac OS X and may work on other unixes but
|
|
57
|
+
definitely won't work on Windows (due to the use of the platform dependent pty_
|
|
58
|
+
module). For usage instructions please refer to the documentation_.
|
|
59
|
+
|
|
60
|
+
.. contents::
|
|
61
|
+
:local:
|
|
62
|
+
|
|
63
|
+
Maintenance status
|
|
64
|
+
------------------
|
|
65
|
+
|
|
66
|
+
This is a continuation of ``capturer``, originally written by Peter Odding
|
|
67
|
+
(`@xolox <https://github.com/xolox>`_), whose last release was 3.0 in 2020.
|
|
68
|
+
The original author is not involved in this continuation. Should he return or
|
|
69
|
+
want the project back, it will be handed over.
|
|
70
|
+
|
|
71
|
+
This continuation is **maintained by one person with AI agents, without
|
|
72
|
+
independent review**. In practice that means:
|
|
73
|
+
|
|
74
|
+
- Changes are written and checked with the help of AI coding agents. A second
|
|
75
|
+
AI model is used as an additional check. That is a tool, not an independent
|
|
76
|
+
human review.
|
|
77
|
+
- There is no second maintainer who reads every change before a release.
|
|
78
|
+
- The goal is to keep the package working on current Python versions. The API
|
|
79
|
+
and behaviour are meant to stay the same. Licence (MIT) and copyright are
|
|
80
|
+
unchanged.
|
|
81
|
+
- Releases are built by GitHub Actions and published to PyPI through Trusted
|
|
82
|
+
Publishing, so every release can be traced to a tagged commit.
|
|
83
|
+
|
|
84
|
+
Install it with ``pip install capturer-ng``. The import name is unchanged
|
|
85
|
+
(``import capturer``), so do not install it next to the original
|
|
86
|
+
``capturer`` distribution: both ship the same files and would overwrite
|
|
87
|
+
each other.
|
|
88
|
+
|
|
89
|
+
If you depend on this package in production, please pin a version and read the
|
|
90
|
+
changelog before upgrading. Reviews, bug reports and co-maintainers are welcome.
|
|
91
|
+
|
|
92
|
+
Status
|
|
93
|
+
------
|
|
94
|
+
|
|
95
|
+
The `capturer` package was developed as a proof of concept over the course of a
|
|
96
|
+
weekend, because I was curious to see if it could be done (reliably). After a
|
|
97
|
+
weekend of extensive testing it seems to work fairly well so I'm publishing the
|
|
98
|
+
initial release as version 1.0, however I still consider this a proof of
|
|
99
|
+
concept because I don't have extensive "production" experience using it yet.
|
|
100
|
+
Here's hoping it works as well in practice as it did during my testing :-).
|
|
101
|
+
|
|
102
|
+
Installation
|
|
103
|
+
------------
|
|
104
|
+
|
|
105
|
+
The `capturer` package is available on PyPI_ which means installation should be
|
|
106
|
+
as simple as:
|
|
107
|
+
|
|
108
|
+
.. code-block:: console
|
|
109
|
+
|
|
110
|
+
$ pip install capturer-ng
|
|
111
|
+
|
|
112
|
+
There's actually a multitude of ways to install Python packages (e.g. the `per
|
|
113
|
+
user site-packages directory`_, `virtual environments`_ or just installing
|
|
114
|
+
system wide) and I have no intention of getting into that discussion here, so
|
|
115
|
+
if this intimidates you then read up on your options before returning to these
|
|
116
|
+
instructions ;-).
|
|
117
|
+
|
|
118
|
+
Getting started
|
|
119
|
+
---------------
|
|
120
|
+
|
|
121
|
+
The easiest way to capture output is to use a context manager:
|
|
122
|
+
|
|
123
|
+
.. code-block:: python
|
|
124
|
+
|
|
125
|
+
import subprocess
|
|
126
|
+
from capturer import CaptureOutput
|
|
127
|
+
|
|
128
|
+
with CaptureOutput() as capturer:
|
|
129
|
+
# Generate some output from Python.
|
|
130
|
+
print "Output from Python"
|
|
131
|
+
# Generate output from a subprocess.
|
|
132
|
+
subprocess.call(["echo", "Output from a subprocess"])
|
|
133
|
+
# Get the output in each of the supported formats.
|
|
134
|
+
assert capturer.get_bytes() == b'Output from Python\r\nOutput from a subprocess\r\n'
|
|
135
|
+
assert capturer.get_lines() == [u'Output from Python', u'Output from a subprocess']
|
|
136
|
+
assert capturer.get_text() == u'Output from Python\nOutput from a subprocess'
|
|
137
|
+
|
|
138
|
+
The use of a context manager (`the with statement`_) ensures that output
|
|
139
|
+
capturing is enabled and disabled at the appropriate time, regardless of
|
|
140
|
+
whether exceptions interrupt the normal flow of processing.
|
|
141
|
+
|
|
142
|
+
Note that the first call to `get_bytes()`_, `get_lines()`_ or `get_text()`_
|
|
143
|
+
will stop the capturing of output by default. This is intended as a sane
|
|
144
|
+
default to prevent partial reads (which can be confusing as hell when you don't
|
|
145
|
+
have experience with them). So we could have simply used ``print`` to show
|
|
146
|
+
the results without causing a recursive "captured output is printed and then
|
|
147
|
+
captured again" loop. There's an optional ``partial=True`` keyword argument
|
|
148
|
+
that can be used to disable this behavior (please refer to the documentation_
|
|
149
|
+
for details).
|
|
150
|
+
|
|
151
|
+
Design choices
|
|
152
|
+
--------------
|
|
153
|
+
|
|
154
|
+
There are existing solutions out there to capture the stdout_ and stderr_
|
|
155
|
+
streams of (Python) processes. The `capturer` package was created for a very
|
|
156
|
+
specific use case that wasn't catered for by existing solutions (that I could
|
|
157
|
+
find). This section documents the design choices that guided the development of
|
|
158
|
+
the `capturer` package:
|
|
159
|
+
|
|
160
|
+
.. contents::
|
|
161
|
+
:local:
|
|
162
|
+
|
|
163
|
+
Intercepts writes to low level file descriptors
|
|
164
|
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
165
|
+
|
|
166
|
+
Libraries like capture_ and iocapture_ change Python's sys.stdout_ and
|
|
167
|
+
sys.stderr_ file objects to fake file objects (using StringIO_). This enables
|
|
168
|
+
capturing of (most) output written to the stdout_ and stderr_ streams from the
|
|
169
|
+
same Python process, however any output from subprocesses is unaffected by the
|
|
170
|
+
redirection and not captured.
|
|
171
|
+
|
|
172
|
+
The `capturer` package instead intercepts writes to low level file descriptors
|
|
173
|
+
(similar to and inspired by `how pytest does it`_). This enables capturing of
|
|
174
|
+
output written to the standard output and error streams from the same Python
|
|
175
|
+
process as well as any subprocesses.
|
|
176
|
+
|
|
177
|
+
Uses a pseudo terminal to emulate a real terminal
|
|
178
|
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
179
|
+
|
|
180
|
+
The `capturer` package uses a pseudo terminal created using `pty.openpty()`_ to
|
|
181
|
+
capture output. This means subprocesses will use ANSI escape sequences because
|
|
182
|
+
they think they're connected to a terminal. In the current implementation you
|
|
183
|
+
can't opt out of this, but feel free to submit a feature request to change this
|
|
184
|
+
:-). This does have some drawbacks:
|
|
185
|
+
|
|
186
|
+
- The use of `pty.openpty()`_ means you need to be running in a UNIX like
|
|
187
|
+
environment for `capturer` to work (Windows definitely isn't supported).
|
|
188
|
+
|
|
189
|
+
- All output captured is relayed on the stderr_ stream by default, so capturing
|
|
190
|
+
changes the semantics of your programs. How much this matters obviously
|
|
191
|
+
depends on your use case. For the use cases that triggered me to create
|
|
192
|
+
`capturer` it doesn't matter, which explains why this is the default mode.
|
|
193
|
+
|
|
194
|
+
There is experimental support for capturing stdout_ and stderr_ separately
|
|
195
|
+
and relaying captured output to the appropriate original stream. Basically
|
|
196
|
+
you call ``CaptureOutput(merged=False)`` and then you use the ``stdout`` and
|
|
197
|
+
``stderr`` attributes of the ``CaptureOutput`` object to get at the output
|
|
198
|
+
captured on each stream.
|
|
199
|
+
|
|
200
|
+
I say experimental because this method of capturing can unintentionally
|
|
201
|
+
change the order in which captured output is emitted, in order to avoid
|
|
202
|
+
interleaving output emitted on the stdout_ and stderr_ streams (which would
|
|
203
|
+
most likely result in incomprehensible output). Basically output is relayed
|
|
204
|
+
on each stream separately after each line break. This means interactive
|
|
205
|
+
prompts that block on reading from standard input without emitting a line
|
|
206
|
+
break won't show up (until it's too late ;-).
|
|
207
|
+
|
|
208
|
+
Relays output to the terminal in real time
|
|
209
|
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
210
|
+
|
|
211
|
+
The main use case of `capturer` is to capture all output of a snippet of Python
|
|
212
|
+
code (including any output by subprocesses) but also relay the output to the
|
|
213
|
+
terminal in real time. This has a couple of useful properties:
|
|
214
|
+
|
|
215
|
+
- Long running operations can provide the operator with real time feedback by
|
|
216
|
+
emitting output on the terminal. This sounds obvious (and it is!) but it is
|
|
217
|
+
non-trivial to implement (an understatement :-) when you *also* want to
|
|
218
|
+
capture the output.
|
|
219
|
+
|
|
220
|
+
- Programs like gpg_ and ssh_ that use interactive password prompts will render
|
|
221
|
+
their password prompt on the terminal in real time. This avoids the awkward
|
|
222
|
+
interaction where a password prompt is silenced but the program still hangs,
|
|
223
|
+
waiting for input on stdin_.
|
|
224
|
+
|
|
225
|
+
Contact
|
|
226
|
+
-------
|
|
227
|
+
|
|
228
|
+
The latest version of `capturer` is available on PyPI_ and GitHub_. The
|
|
229
|
+
documentation is hosted on `Read the Docs`_ and includes a changelog_. For bug
|
|
230
|
+
reports please create an issue on GitHub_. Please do not contact the
|
|
231
|
+
original author about problems with this continuation.
|
|
232
|
+
|
|
233
|
+
License
|
|
234
|
+
-------
|
|
235
|
+
|
|
236
|
+
This software is licensed under the `MIT license`_.
|
|
237
|
+
|
|
238
|
+
© 2020 Peter Odding.
|
|
239
|
+
|
|
240
|
+
A big thanks goes out to the pytest_ developers because pytest's mechanism for
|
|
241
|
+
capturing the output of subprocesses provided inspiration for the `capturer`
|
|
242
|
+
package. No code was copied, but both projects are MIT licensed anyway, so it's
|
|
243
|
+
not like it's very relevant :-).
|
|
244
|
+
|
|
245
|
+
.. External references:
|
|
246
|
+
.. _capture: https://pypi.org/project/capture
|
|
247
|
+
.. _changelog: https://capturer.readthedocs.io/en/latest/changelog.html
|
|
248
|
+
.. _documentation: https://capturer.readthedocs.io
|
|
249
|
+
.. _get_bytes(): https://capturer.readthedocs.io/en/latest/api.html#capturer.CaptureOutput.get_bytes
|
|
250
|
+
.. _get_lines(): https://capturer.readthedocs.io/en/latest/api.html#capturer.CaptureOutput.get_lines
|
|
251
|
+
.. _get_text(): https://capturer.readthedocs.io/en/latest/api.html#capturer.CaptureOutput.get_text
|
|
252
|
+
.. _GitHub: https://github.com/marco8154/python-capturer-ng
|
|
253
|
+
.. _gpg: https://en.wikipedia.org/wiki/GNU_Privacy_Guard
|
|
254
|
+
.. _how pytest does it: https://pytest.org/latest/capture.html
|
|
255
|
+
.. _iocapture: https://pypi.org/project/iocapture
|
|
256
|
+
.. _MIT license: http://en.wikipedia.org/wiki/MIT_License
|
|
257
|
+
.. _per user site-packages directory: https://www.python.org/dev/peps/pep-0370/
|
|
258
|
+
.. _pty.openpty(): https://docs.python.org/2/library/pty.html#pty.openpty
|
|
259
|
+
.. _pty: https://docs.python.org/2/library/pty.html
|
|
260
|
+
.. _PyPI: https://pypi.org/project/capturer-ng
|
|
261
|
+
.. _pytest: https://pypi.org/project/pytest
|
|
262
|
+
.. _Read the Docs: https://capturer.readthedocs.io
|
|
263
|
+
.. _ssh: https://en.wikipedia.org/wiki/Secure_Shell
|
|
264
|
+
.. _stderr: https://en.wikipedia.org/wiki/Standard_streams#Standard_error_.28stderr.29
|
|
265
|
+
.. _stdin: https://en.wikipedia.org/wiki/Standard_streams#Standard_input_.28stdin.29
|
|
266
|
+
.. _stdout: https://en.wikipedia.org/wiki/Standard_streams#Standard_output_.28stdout.29
|
|
267
|
+
.. _StringIO: https://docs.python.org/2/library/stringio.html
|
|
268
|
+
.. _sys.stderr: https://docs.python.org/2/library/sys.html#sys.stderr
|
|
269
|
+
.. _sys.stdout: https://docs.python.org/2/library/sys.html#sys.stdout
|
|
270
|
+
.. _the with statement: https://docs.python.org/2/reference/compound_stmts.html#the-with-statement
|
|
271
|
+
.. _virtual environments: http://docs.python-guide.org/en/latest/dev/virtualenvs/
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
capturer/__init__.py,sha256=ycPiDmaHgBxiKikANGsZNIpze9E7Grg1ZWo0Ccjvccg,29754
|
|
2
|
+
capturer/tests.py,sha256=-PddPu452nY5rKTPWWcKOijit9lgBX6lnKne-DIMhuc,8365
|
|
3
|
+
capturer_ng-4.0.dist-info/METADATA,sha256=LkmD8kMIV1SY81HQbDP01Yz6B4k6q-9Dlr-kOxDrRsw,12954
|
|
4
|
+
capturer_ng-4.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
5
|
+
capturer_ng-4.0.dist-info/licenses/LICENSE.txt,sha256=C-9P-xhVtlVwME8gGMbUTkurl71d-HFuzXgAAU1xcmc,1056
|
|
6
|
+
capturer_ng-4.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
Copyright (c) 2020 Peter Odding
|
|
2
|
+
|
|
3
|
+
Permission is hereby granted, free of charge, to any person obtaining
|
|
4
|
+
a copy of this software and associated documentation files (the
|
|
5
|
+
"Software"), to deal in the Software without restriction, including
|
|
6
|
+
without limitation the rights to use, copy, modify, merge, publish,
|
|
7
|
+
distribute, sublicense, and/or sell copies of the Software, and to
|
|
8
|
+
permit persons to whom the Software is furnished to do so, subject to
|
|
9
|
+
the following conditions:
|
|
10
|
+
|
|
11
|
+
The above copyright notice and this permission notice shall be
|
|
12
|
+
included in all copies or substantial portions of the Software.
|
|
13
|
+
|
|
14
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
15
|
+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
|
16
|
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
|
17
|
+
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
|
18
|
+
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
|
19
|
+
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
|
20
|
+
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|