Catch the stdout
The following example catches the python stdout and stderr:
basic.py
import syncstream
# Initialize the buffer.
buffer = syncstream.LineBuffer(10)
# The buffer itself is a context supporting stdout/stderr redirecting.
with buffer:
for i in range(20):
print('Message', f'"{i:02d}".')
print('Line break\nin middle.', end='')
print('No line break.', end='')
# Check the results
messages = buffer.read()
for mitem in messages:
print(mitem)
In the definition of the buffer, we set the maximal number of catched lines as 10
:
buffer = syncstream.LineBuffer(10)
The buffer instance could be passed to the redirect context. Inside the context, the print
function would be redirected to the buffer. Each time a new line is detected, a new record item would be created by the buffer. The rules for detecting the new lines are the same as those of str.splitlines
in the stdlib.
After catching all lines, the results could be returned by
messages = buffer.read()
Each item of messages
is a str
representing a line catched inside the context.