有没有办法指定函数应打印其输出的输出单元格?
在我的具体情况下,我有一些线程正在运行,每个线程都有一个记录器。记录器输出打印在任何正在运行的单元上,从而干扰该单元的预期输出。例如,有没有办法强制记录器仅在
cell #1
上打印?
您可以使用以下方法:
logging.Handler
,它会累积所有日志输出,例如在 queue.Queue
中。假设我们想在第一个单元格的底部打印,单元格 1 可能如下所示:
# Cell 1
import logging, queue, threading, time
log_queue = queue.Queue()
class QueueHandler(logging.Handler):
def emit(self, record):
log_queue.put(record)
logging.getLogger().addHandler(QueueHandler())
def print_logs():
while True:
try:
print(log_queue.get(block=True, timeout=.1).getMessage())
except queue.Empty:
continue
threading.Thread(target=print_logs, daemon=True).start() # Print at the bottom of cell 1
在单元 2 中,我们将模拟一些活动:
# Cell 2
def log_activity_1():
while True:
logging.getLogger().warning("Activity 1")
time.sleep(1)
threading.Thread(target=log_activity_1, daemon=True).start()
同样,在单元格 3 中:
# Cell 3
def log_activity_2():
while True:
logging.getLogger().warning("Activity 2")
time.sleep(2)
threading.Thread(target=log_activity_2, daemon=True).start()
输出将如预期的那样(对于每个记录的“活动 2”,我们将看到大约两次记录的“活动 1”,因为我们在前者中睡眠 2 秒,在后者中睡眠 1 秒): 一个缺点:在给定的设置中,停止处理的唯一方法是关闭或重新启动内核。为了缓解这种情况,我们需要确保线程已停止,这些线程当前正在无限循环中运行。