sanchit
sanchit

Reputation: 2528

Print message before progress bar using tqdm

In my python project I'm using tqdm module to display a progress bar. I want to print a persistent message on the line before the progress bar.

The set_description method prints the message on the same line, whilte tqdm.write creates a new line.

Using set_description

$ python pbar.py {Task_1 message} 3%|████ ]

Is is possible to achieve this

$ python pbar.py {Task_1 message} 3%|████ ]

Edit:

from tqdm import tqdm

pbar = tqdm(m_list)
for item in m_list:
   # Do work
   pbar.update(1)
pbar.close()

Upvotes: 7

Views: 10764

Answers (2)

Ébe Isaac
Ébe Isaac

Reputation: 12391

This is a probable workaround which worked for me:

print("Your message", flush=True)

Upvotes: 0

Jean-François Fabre
Jean-François Fabre

Reputation: 140276

Simple example with a loop:

import tqdm,time

for i in tqdm.tqdm(range(9),desc="{Task_1 message}"):
    time.sleep(0.1)

final output:

{Task_1 message}: 100%|##############################################| 9/9 [00:00<00:00,  9.99it/s]

If you add \n to the description, it will trash your output like this:

{Task_1 message}
{Task_1 message}                                            | 0/9 [00:00<?, ?it/s]
{Task_1 message}                                    | 1/9 [00:00<00:00,  9.99it/s]
{Task_1 message}#                                   | 2/9 [00:00<00:00,  9.99it/s]
{Task_1 message}######                              | 3/9 [00:00<00:00,  9.99it/s]
{Task_1 message}###########                         | 4/9 [00:00<00:00,  9.99it/s]
{Task_1 message}################                    | 5/9 [00:00<00:00,  9.99it/s]
{Task_1 message}#####################               | 6/9 [00:00<00:00,  9.96it/s]
{Task_1 message}##########################          | 7/9 [00:00<00:00,  9.97it/s]
{Task_1 message}###############################     | 8/9 [00:00<00:00,  9.98it/s]
: 100%|#############################################| 9/9 [00:00<00:00,  9.98it/s]

The only thing you can do is to print the description first, and run the task without description, as you can only delete the current line in the terminal.

import tqdm,time

print("{Task_1 message}")
for i in tqdm.tqdm(range(9)):
    time.sleep(0.1)

As previously said, you can only delete the current line in the terminal (using \r), there are numerous topics about that limitation on SO.

The alternative is using curses, but that's a completely different approach.

Upvotes: 6

Related Questions