5 from __future__
import with_statement
7 from contextlib
import contextmanager, nested
8 from threading
import Thread
10 from tempfile
import mkdtemp
11 from os.path
import join
as pjoin
12 from os
import (dup, fdopen, open
as osopen, O_NONBLOCK, O_RDONLY, remove,
14 from fcntl
import fcntl, F_GETFL, F_SETFL
15 from select
import select
16 from sys
import stdout, stderr
18 from ctypes
import PyDLL, CDLL, c_void_p, c_char_p, py_object
20 from six
import print_
33 PyFile_AsFile =
make_fn(pyapi.PyFile_AsFile, FILE_p, py_object)
34 freopen =
make_fn(this_exe.freopen, FILE_p, c_char_p, c_char_p, FILE_p)
39 Create a fifo in a temporary place.
42 filename = pjoin(tmpdir,
'myfifo')
46 print_(
"Failed to create FIFO: %s" % e, file=stderr)
59 flags = fcntl(fd, F_GETFL)
60 if flags & O_NONBLOCK:
62 fcntl(fd, F_SETFL, flags)
66 Sit there, reading lines from the pipe `filename`, sending those for which
67 `filter_()` returns False to `real_stdout`
69 with fdopen(osopen(filename, O_NONBLOCK | O_RDONLY))
as fd:
71 rlist, _, _ =
select([fd], [], [])
78 filt_content.write(line)
80 real_stdout.write(line)
85 Operate a read_thread_func in another thread. Block with statement exit
86 until the function completes.
88 reader_thread = Thread(target=reader_thread_func, args=args)
96 def silence(filter_=lambda line:
True, file_=stdout):
98 Prevent lines matching `filter_` ending up on `file_` (defaults to stdout)
107 if not isinstance(file_, file):
112 saved_stdout = dup(file_.fileno())
115 from io
import StringIO
116 filt_content = StringIO()
118 with nested(fdopen(saved_stdout,
"w"),
fifo())
as (real_stdout, filename):
121 real_stdout, filt_content)
124 freopen(filename,
"w", stdout_file)
129 freopen(
"/dev/fd/%i" % saved_stdout,
"w", stdout_file)
132 print_(
"Hit an exception. Filtered content:")
133 print_(filt_content.getvalue())
138 from sys
import stdout, stderr
139 with nested(
silence(filter_, stdout),
silence(filter_, stderr))
as (so, se):
144 def filter_hello(line):
145 if line.startswith(
"Data source lookup using"):
148 print_(
"Before with block..")
151 from DQUtils.db
import Databases
152 f = Databases.get_folder(
"DQMFONL")
153 print_(
"Sensible stuff!")
157 print_(
"I am after the silence block")
161 print_(
"Before silence.")
163 with silence()
as filt_content:
165 raise RuntimeError(
"Error.")
168 print_(
"After silence")
169 print_(
"Stuff?", len(filt_content.getvalue()))
171 if __name__ ==
"__main__":