[New-bugs-announce] [issue24500] xontextlib.redirect_stdout should redirect C output

Zahari Dim report at bugs.python.org
Wed Jun 24 18:03:02 CEST 2015


New submission from Zahari Dim:

It is common to have an inflexible C wrapper with lots of undesired output. However it is not so trivial to supress (or redirect) that output from Python in a selective way. contextlib.redirect_stdout doesn't help, since it only changes sys.sdout, without touching the actual file descriptor. The following worked for my use case, which I adapted from here http://eli.thegreenplace.net/2015/redirecting-all-kinds-of-stdout-in-python/:

import sys
import os
from contextlib import contextmanager, redirect_stdout

@contextmanager
def supress_stdout():
    devnull = open(os.devnull, 'wb')
    try:
        stdout_flieno = sys.stdout.fileno()
    except ValueError:
        redirect = False
    else:
        redirect = True
        sys.stdout.flush()
        #sys.stdout.close()
        devnull_fileno = devnull.fileno()
        saved_stdout_fd = os.dup(stdout_flieno)
        os.dup2(devnull_fileno, stdout_flieno)

    with redirect_stdout(devnull):
        yield
    if redirect:
        os.dup2(stdout_flieno, saved_stdout_fd)

----------
components: Extension Modules, Library (Lib)
messages: 245760
nosy: Zahari.Dim
priority: normal
severity: normal
status: open
title: xontextlib.redirect_stdout should redirect C output
type: enhancement
versions: Python 3.4

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue24500>
_______________________________________


More information about the New-bugs-announce mailing list