为了克服这个问题,我使用了以下条件import
,它适用于可能在 Jupyter Notebook或控制台中运行的代码(如果不以交互方式运行,则不执行任何操作):
# progress.py
import sys
def tqdm(iterable, **kwargs):
"""Fake progress function."""
return iterable
# check if running notebook and use notebook backend for tqdm progress bar
if 'IPython' in sys.modules:
from IPython import get_ipython
from IPython.display import display_javascript, Javascript
from tqdm import tqdm
ip = get_ipython()
if 'IPKernelApp' in ip.config:
monkey_patch = f"""
from tqdm import tqdm_notebook as tqdm
import {__name__} as module
module.tqdm = tqdm
"""
monkey_patch = ';'.join(x.strip() for x in monkey_patch.strip().split('\n'))
display_javascript(Javascript(f"""IPython.notebook.kernel.execute("{monkey_patch}");"""))
然后使用它:
$ jupyter console # or ipython3
In [1]: import progress
In [2]: list(progress.tqdm(range(10)))
100%|██████████| 10/10 [00:00<00:00, 120873.31it/s]
Out[2]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]