Message245760
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) |
|
Date |
User |
Action |
Args |
2015-06-24 16:03:02 | Zahari.Dim | set | recipients:
+ Zahari.Dim |
2015-06-24 16:03:02 | Zahari.Dim | set | messageid: <1435161782.93.0.989546707262.issue24500@psf.upfronthosting.co.za> |
2015-06-24 16:03:02 | Zahari.Dim | link | issue24500 messages |
2015-06-24 16:03:02 | Zahari.Dim | create | |
|