[Python] Import prints, even when stdout and stderr are suppressed

Discussão em 'Python' iniciado por Stack, Agosto 28, 2025.

  1. Stack

    Stack Membro Participativo

    I have a module that I need to use. However, when it is imported, it helpfully prints out some status information.

    > import problematic_module
    Connected to local cache!
    Detected version 1.0.0!
    <several more lines of startup info>
    >


    I want to suppress this, so a CLI tool does not have unnecessary cruft surrounding the output. There are many questions about how to suppress console output, and a popular solution is something like this.:

    import contextlib
    import os
    import sys

    @contextlib.contextmanager
    def silent_legacy_startup():
    try:
    old_stdout = sys.__stdout__
    old_stderr = sys.__stderr__
    with open(os.devnull, "w") as devnull:
    with contextlib.redirect_stdout(devnull):
    with contextlib.redirect_stderr(devnull):

    sys.__stdout__ = devnull
    sys.__stderr__ = devnull

    # PLEASE BE QUIET.
    yield
    finally:
    sys.__stdout__ = old_stdout
    sys.__stderr__ = old_stderr

    with silent_legacy_startup():
    import problematic_module


    While this makes the module import quieter, it still manages to print:

    Connected to local cache!
    Detected version 1.0.0!


    The offending text is coming from stdout:

    $ python silently_import.py 1> stdout.txt 2> stderr.txt
    $ cat stdout.txt
    Connected to local cache!
    Detected version 1.0.0!
    $ cat stderr.txt
    $

    Partial solution:


    Since redirection silences the output, the obvious step seems to be to redirect fd 1 itself. E.g., dup2(1, 5), dup2(NULL, 1), dup2(5, 1) to restore stdout once done. Here's my attempt at that:

    def noisy_code():
    print("hello from print!")
    sys.stdout.write("hello from stdout!\n")
    sys.__stdout__.write("hello from __stdout__!\n")
    with os.fdopen(1, 'w') as fd_1:
    fd_1.write("hello from fdopen(1)!\n")

    @contextlib.contextmanager
    def silence_everything():
    try:
    stdout_fd = sys.stdout.fileno()
    dup_stdout = os.dup(stdout_fd)
    with open(os.devnull, "w") as devnull:
    os.dup2(devnull.fileno(), stdout_fd)
    yield
    finally:
    os.dup2(dup_stdout, stdout_fd)
    os.close(dup_stdout)

    with silence_everything():
    noisy_code()


    Unfortunately, this crashes, printing:

    Traceback (most recent call last):
    ...
    print("hello from print!")
    OSError: [WinError 1] Incorrect function


    My guess is that this style of dup2 swapping is a unix-only trick and I'm missing the windows equivalent.

    Continue reading...

Compartilhe esta Página