问题描述
运行 MetaFlow Flows 时,tqdm
进度条直到最后一次迭代才会显示,这违背了衡量进度的目的。有没有办法强制 MetaFlow 打印出 tqdm 更新?
解决方法
问题是 tqdm
写入 stderr,但 MetaFlow 隐藏输出到 stderr。该解决方案需要两个技巧:使用上下文管理器将 tqdm
输出重定向到记录器,并将该记录器设置为写入 stderr。
示例:
import logging
import sys
from time import sleep
import tqdm
from metaflow import FlowSpec,step
from tqdm.contrib.logging import tqdm_logging_redirect
# stream to stdout needed because MetaFlow hides output to stderr :C
logging.basicConfig(level=logging.INFO,stream=sys.stdout)
class TQDMFlow(FlowSpec):
@step
def start(self):
print("Training...")
with tqdm_logging_redirect(): # this context manager redirects tqdm output to logging
for _ in tqdm.tqdm(range(20)):
sleep(0.25)
self.next(self.end)
@step
def end(self):
pass
if __name__ == "__main__":
TQDMFlow()
我还尝试使用 tqdm_logging_redirect
将输出直接重定向到标准输出(没有 logging
上下文管理器或 tqdm(range(n),file=sys.stdout)
),但没有奏效。