简体   繁体   中英

tqdm color bar shows red if using break in Jupyter notebook

I use tqdm from tqdm.notebook to display a progress bar for iteration through lines of a file. I supply the total argument to give the number of iterations that will be performed (since I know it upfront) so the progress can be accurately displayed.

I use a break to stop at the maximum number of desired iterations (lines of the file to read).

Despite the fact that the number of iterations performed is equal to the value supplied to total in tqdm and the progress bar shows the maximum number of iterations have been performed (eg 11/11 in the example; see image), the bar is displayed in red (not green) indicating premature termination / an error.

I have already tried to assign the tqdm object to a variable and explicitly close the iterator in the condition before the break as per this related question .

How can I make the progress bar display correctly?

from tqdm.notebook import tqdm
LETTERS = list('ABCDEFGHIJKL')
for idx, letter in enumerate(tqdm(LETTERS, total=len(LETTERS)-1)):
    print(letter)
    if idx >= len(LETTERS) - 1:
        break

在此处输入图像描述


Version information (if helpful)

IPython: 8.1.1 ipykernel: 6.9.2 ipywidgets: 7.7.0 jupyter_client: 7.1.2 jupyter_core: 4.9.2 jupyter_server: not installed jupyterlab: not installed nbclient: 0.5.13 nbconvert: 6.4.4 nbformat: 5.2.0 notebook: 6.4.10 qtconsole: 5.2.2 traitlets: 5.1.1

Running with Python 3.8.10.

Because the break is in the last iteration, tqdm assumes that the loop stopped unintendedly, even if the loop is finished from the semantic side.

If you want to have a green progress bar in the end structure your code like this

from tqdm.notebook import tqdm

LETTERS = list('ABCDEFGHIJKL')
for idx, letter in enumerate(tqdm(LETTERS, total=len(LETTERS))):
    if idx == len(LETTERS):
        break
    print(letter)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM