【问题标题】:tqdm failure with Jupyter NotebookJupyter Notebook 的 tqdm 失败
【发布时间】:2017-06-09 20:24:12
【问题描述】:

tqdm 是我最喜欢的 Python 包之一,但我有一个烦人的问题,我想弄清楚这是否是我的错。

在使用Jupyter Notebook 运行tqdm 循环并运行RunTime Error 时,恢复非常困难 - 修复错误并重新运行循环会导致 multiline 打印,而不是 @ 987654325@原单行。恢复的唯一方法是重新启动内核,这不是很有用。

还有其他解决方案吗?

我无法故意重现该问题,但这里有一个可能导致该问题的示例代码:

from tqdm import trange
s=0
for i in trange(100):
    s+=i
    if i==10:
        raise ValueError

然后重新运行单元格。

【问题讨论】:

  • 你解决过这个问题吗?每当我中断一个单元格时,我都会看到类似的问题(实际上是 KeyboardInterrupt

标签: python jupyter tqdm


【解决方案1】:

为了克服这个问题,我使用了以下条件 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]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-16
    • 2021-05-14
    • 1970-01-01
    • 2019-04-14
    • 2021-08-13
    • 2015-10-15
    • 1970-01-01
    • 2021-04-21
    相关资源
    最近更新 更多