matohak
matohak

Reputation: 585

How to get tqdm to print to the same line regardless of terminal window size?

I'm using tqdm to draw a progress bar and would like tqdm to overwrite the same line in the terminal regardless of the window size. Consider the following code:

from tqdm import trange
from time import sleep
t = trange(100, desc='Bar desc', leave=True)
for i in t:
    t.set_description("Bar desc (file %i)" % i)
    t.refresh() # to show immediately the update
    sleep(0.01)

When the width of my terminal window is wider than "Bar desc (file %i)" , tqdm would print the progress bar as I desire. However, if I reduce the width of my terminal window, tqdm would print to two lines. Every tqdm update would print to a new line. Is there any way round to get tqdm to print to the same two lines even if I resize my terminal?

I'm using bash terminal in Ubuntu.

Upvotes: 5

Views: 1854

Answers (2)

framist
framist

Reputation: 1

You may can use the arg dynamic_ncols

dynamic_ncols : bool, optional

If set, constantly alters ncols and nrows to the environment (allowing for window resizes) [default: False].

e.g.

from tqdm import trange
from time import sleep
t = trange(100, desc='Bar desc', dynamic_ncols=True)
for i in t:
    t.set_description("Bar desc (file %i)" % i)
    t.refresh() # to show immediately the update
    sleep(0.01)

Upvotes: 0

Léa Gris
Léa Gris

Reputation: 19665

There are multiple options:

Either query terminal width and trim your bar accordingly linewidth=$(($(tput cols) - 1)) Either disable line-wrap

disable line-wrap: ncurses tput rmam ANSI: '\x1B[?7l`

enable line-wrap: ncursestput smam ANSI: '\x1B[?7h`

Upvotes: 0

Related Questions