<commit_before>import os
from tempfile import SpooledTemporaryFile
from contextlib import contextmanager

@contextmanager
def redirect_stream(output_stream, destination):
    """
    Redirect anything written to ``output_stream`` (typically ``sys.stdin`` or
    ``sys.stdout``) to ``destination`` for the duration of this context.

    ``destination`` must provide a ``write()`` method.
    """
    while not isinstance(output_stream, file):
        # Looks like this is an XUnit Tee object. Try and find the "real"
        # stderr in its history.
        output_stream = output_stream._streams[-1]

    old_stream = os.dup(output_stream.fileno())
    with SpooledTemporaryFile() as s:
        os.dup2(s.fileno(), output_stream.fileno())
        yield
        s.seek(0)
        destination.write(s.read())
    os.dup2(old_stream, output_stream.fileno())
<commit_msg>Only use XUnit workaround if we have a _streams attribute<commit_after>import os
from tempfile import SpooledTemporaryFile
from contextlib import contextmanager

@contextmanager
def redirect_stream(output_stream, destination):
    """
    Redirect anything written to ``output_stream`` (typically ``sys.stdin`` or
    ``sys.stdout``) to ``destination`` for the duration of this context.

    ``destination`` must provide a ``write()`` method.
    """
    # Workaround for XUnit "Tee" objects.
    if hasattr(output_stream, "_streams"):
        while not isinstance(output_stream, file):
            output_stream = output_stream._streams[-1]

    old_stream = os.dup(output_stream.fileno())
    with SpooledTemporaryFile() as s:
        os.dup2(s.fileno(), output_stream.fileno())
        yield
        s.seek(0)
        destination.write(s.read())
    os.dup2(old_stream, output_stream.fileno())

{'fraction_non_alphanumeric': 0.11224489795918367, 'fraction_numerical': 0.0045351473922902496, 'mean_word_length': 3.608355091383812, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2738494', 'n_tokens_mistral': 520, 'n_tokens_neox': 511, 'n_words': 146}