Search code examples
pythonpython-3.xterminalpycharmtqdm

importing tqdm disables text formatting using termcolor


I think my problem is parallel to this issue

I'm using termcolor to format terminal text. termcolor basically just wraps your string in ANSI codes that the terminal then interprets. The snippet

from termcolor import cprint

cprint('Hello, World!', 'green', attrs=['bold'])

green text

works fine, but importing tqdm results in white text:

from tqdm import tqdm
from termcolor import cprint
cprint('Hello, World!', 'green', attrs=['bold'])

white text

The ANSI codes are still there, but the terminal is no longer parsing them.

tqdm is unfortunately deeply entrenched in my package, so I can't just get rid of the import. What is the package doing to the terminal that changes the behavior, and how can I disable it when I need to?

Using python 3.5, tqdm 4.15, PyCharm 2017.2.3 on Windows 10


Solution

  • The problem was not with tqdm, but with colorama which is used internally. On Windows / PhCharm there are known issues with the colorama.init() method (see https://youtrack.jetbrains.com/issue/PY-16927, https://github.com/tartley/colorama/issues/79)

    Fortunately, as long as you use .init(strip=False) everything works fine, and the colorama folks have provided a convenient .deinit() method to reverse whatever tqdm uses on import. The following works:

    from tqdm import tqdm
    import colorama
    from termcolor import cprint
    
    colorama.deinit()
    colorama.init(strip=False)
    cprint('Hello, World!', 'green', attrs=['bold'])