Python 3.5: Colorama 不识别 Windows 环境

Python 3.5: Colorama does not recognize Windows environment

我将 Python 安装从 3.4 更新到 3.5(CPython 64 位在 Windows 7 Enterprise 64 位上)。在那次更新之后,colorama 停止将 ANSI 转义序列转换为 Win32 API 调用以更改命令行终端颜色。

需要显式 colorama.init(convert=True) 才能获得彩色输出。我试图缩小错误范围:

  1. 自 Python 3.5 更新后出现
  2. 如果我使用转换选项隐式调用 init(),就可以解决这个问题。
  3. 从 cmd.exe 启动彩色 Python 脚本按预期工作。
  4. 从 powershell.exe 启动彩色 Python 脚本会显示所描述的行为。

所以我认为如果从 Powershell 启动,Python 无法识别 windows 环境?

任何人都可以重现这种奇怪的行为吗?我该如何解决它。启用 convert 会在 Linux.

上出现问题

我搜索了 colorama 0.3.3 源并找到了确定它是否为 运行 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
....

一个条件是是否设置了 TERM 环境变量。不幸的是,我的 PowerShell 控制台声称是一个 cygwin 终端。

但是我从来没有自己安装过cygwin。所以我必须搜索哪个程序安装了 cygwin 并将其注册到我的 PowerShell !?!

编辑:

我发现,PoSh-Git 注册了一个 TERM 变量。作为解决方法,我在加载 PoSh-Git 后立即添加了 rm env:TERM 行。

在 PoSh-Git 更新后变量被删除,所以我也删除了我的解决方法。