分离tmux会话后,如何让Jupyter Notebook的tqdm进度条持续输出?
问题描述
我在tmux会话中运行Jupyter Notebook,测试分离会话后tqdm进度条的输出保留情况,操作步骤如下:
- 创建tmux会话:
tmux new-session -s mysession - 在会话内启动Jupyter Notebook:
jupyter notebook - 创建.ipynb文件并写入测试代码:
from tqdm import tqdm import time with tqdm(total=10000) as pbar: for i in range(10000): time.sleep(1) pbar.update(1) print('DONE')
运行时能正常查看进度条,但执行Ctrl-b d分离会话并关闭浏览器标签后,重新打开Notebook链接,发现进程仍在运行,但tqdm进度条停留在关闭时的状态。想问有没有办法实现分离tmux会话后重新打开Jupyter Notebook时,tqdm进度条等输出能持续显示?
原因分析
Jupyter的普通终端式输出(包括默认tqdm进度条)依赖WebSocket实时推送给前端,关闭浏览器重连时,前端只会加载历史输出缓存,后续的进度更新不会主动同步——因为默认tqdm是为终端环境设计的,未适配Jupyter的持久化输出机制。
解决方法
方法1:使用tqdm的Jupyter专用版本
替换为tqdm.notebook.tqdm,它专门适配Jupyter环境,通过交互式输出系统更新进度,重连后前端会自动同步最新状态。修改后的代码:
from tqdm.notebook import tqdm import time with tqdm(total=10000) as pbar: for i in range(10000): time.sleep(1) pbar.update(1) print('DONE')
方法2:文件记录+实时读取进度
如果不想改动tqdm使用方式,可将进度写入文件,再通过单独单元格实时读取:
- 主代码修改为写入进度到文件:
from tqdm import tqdm import time with open('progress.txt', 'w') as f: with tqdm(total=10000) as pbar: for i in range(10000): time.sleep(1) pbar.update(1) f.write(f"{pbar.n}\n") f.flush() # 确保内容立即写入文件 print('DONE')
- 新建单元格运行以下代码实时读取:
import time while True: try: with open('progress.txt', 'r') as f: lines = f.readlines() if lines: current = int(lines[-1]) print(f"当前进度: {current}/10000", end='\r') time.sleep(1) except FileNotFoundError: print("进度文件未找到,等待任务启动...") time.sleep(2) except ValueError: continue
重连Notebook后运行该单元格即可查看最新进度。
方法3:使用ipywidgets原生进度条
Jupyter的ipywidgets组件支持持久化交互式输出,重连后自动同步状态:
- 先安装并启用组件:
pip install ipywidgets jupyter nbextension enable --py widgetsnbextension
- 编写代码:
from ipywidgets import IntProgress from IPython.display import display import time progress = IntProgress(min=0, max=10000) display(progress) for i in range(10000): time.sleep(1) progress.value += 1 print('DONE')
内容的提问来源于stack exchange,提问作者Borealis
相关产品推荐
相关产品推荐

