Search code examples
pythontqdm

Preventing tqdm from printing anything after error


when handling errors in a tqdm loop, I'd like error messages to be the last thing printed. A MWE:

import tqdm
import sys

for i in tqdm.tqdm(range(10)):

    if i == 3:

        print('error')

        sys.exit(1)

When running this, tqdm still prints a progress bar after the "error" message. Is it possible to avoid this (so that "error" is the last thing shown)?

EDIT: I'm actually calling sys.exit from different external modules that know nothing of tqdm, and I don't want to have a global variable with the tqdm object. Maybe I'm asking for too much...

Cheers.


Solution

  • Yes. call close() and make sure leave is False.

    See: https://tqdm.github.io/docs/tqdm/#close