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

import sys
import os
from contextlib import contextmanager, redirect_stdout

def supress_stdout():
    devnull = open(os.devnull, 'wb')
        stdout_flieno = sys.stdout.fileno()
    except ValueError:
        redirect = False
        redirect = True
        devnull_fileno = devnull.fileno()
        saved_stdout_fd = os.dup(stdout_flieno)
        os.dup2(devnull_fileno, stdout_flieno)

    with redirect_stdout(devnull):
    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 <>
Python-bugs-list mailing list

Reply via email to