Search code examples
pythonpowershellpython-3.5colorama

Python 3.5: Colorama does not recognize Windows environment


I updated my Python installation from 3.4 to 3.5 (CPython 64-bit on Windows 7 Enterprise 64-bit). After that update colorama stopped to translate ANSI escape sequences into Win32 API calls to change the command line terminal colors.

An explicit colorama.init(convert=True) is needed to get colored outputs. I tried to narrow the error down:

  1. It showed up since the Python 3.5 update
  2. It can be worked around if I implicitly call init() with the convert option.
  3. Launching a colored Python script from cmd.exe works as expected.
  4. Launching a colored Python script from powershell.exe shows the described behavior.

So I assume Python does not recognize a windows environment if launched from Powershell?

Can anybody reproduce this odd behavior? How should I fix it. Enabling convert will give problems on Linux.


Solution

  • I searched the colorama 0.3.3 sources and found the code for determining if it's running windows:

    ...
    on_windows = os.name == 'nt'
    on_emulated_windows = on_windows and 'TERM' in os.environ
    
    # should we strip ANSI sequences from our output?
    if strip is None:
      strip = on_windows and not on_emulated_windows
    self.strip = strip
    
    # should we should convert ANSI sequences into win32 calls?
    if convert is None:
      convert = on_windows and not wrapped.closed and not on_emulated_windows and is_a_tty(wrapped)
    self.convert = convert
    ....
    

    One condition is if there is a TERM environment variable set. Unfortunately my PowerShell console claims to be a cygwin terminal.

    But I never installed cygwin by myself. So I've to search which program installed cygwin and registered it in my PowerShell !?!

    Edit:

    I found out, that PoSh-Git registers a TERM variable. As a workaround, I added a rm env:TERM line immediately after PoSh-Git was loaded.

    After a PoSh-Git update the variable was removed, so I removed my workaround, too.