I have worker thread(s) that use the logger. In the main thread, I occasionally need to ask the user to take some action. Which means I need to suppress the logger from actually printing until the user has a chance to make a decision. But there doesn't seem to be something like a logging.pause() method.
This is what I have for now, but I'm concerned about the atomicity of the unpause method: while flushing the pausebuffer, the other thread fills it up and somewhere between the end of the while loop but before self._pause = False is set, an item is added to the buffer and gets lost.
I'm not sure that this is the best approach in general and am looking for suggestions on a better way of handling my needs.
This is what I have for now, but I'm concerned about the atomicity of the unpause method: while flushing the pausebuffer, the other thread fills it up and somewhere between the end of the while loop but before self._pause = False is set, an item is added to the buffer and gets lost.
I'm not sure that this is the best approach in general and am looking for suggestions on a better way of handling my needs.
Code:
import logging
import sys
import threading
import time
from collections import deque
# how to atomically: empty pausebuffer, write from buffer, set unpause
class PausableOutput(object):
def __init__(self, stream):
self._stream = stream
self._pause = False
self._pausebuffer = deque()
def write(self, object):
if self._pause:
self._pausebuffer.append(object)
else:
self._stream.write(object)
def writelines(self, lst):
if self._pause:
self._pausebuffer.extend(lst)
else:
self._stream.writelines(lst)
def pause(self):
self._pause = True
self._stream.flush()
def unpause(self):
self._empty_buffer()
self._pause = False
self._stream.flush()
def _empty_buffer(self):
while self._pausebuffer:
self._stream.write(self._pausebuffer.popleft())
def flush(self):
if not self._pause:
self._stream.flush()
def close(self):
self._stream.close()
@property
def closed(self):
return self._stream.closed
def noisy_thread(l, msg="noisy thread", sec=0.5):
while l[0]:
logging.error(msg)
time.sleep(sec)
if __name__ == '__main__':
outstream = PausableOutput(sys.stderr)
logging.basicConfig(stream=outstream)
l = [True]
nthrd = threading.Thread(target=noisy_thread, args=(l,))
nthrd.start()
while True:
outstream.pause()
ans = input("Break now?: ")
print(ans)
outstream.unpause()
if ans.strip().lower().startswith('y'):
l[0] = False
break
nthrd.join()