Skip to main content
 首页 » 编程设计

python 3.5 : Colorama does not recognize Windows environment

2024年10月24日13sxdcgaq8080

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

需要一个明确的 colorama.init(convert=True) 来获得彩色输出。我试图缩小错误范围:

  1. 自 Python 3.5 更新后出现
  2. 如果我使用 convert 选项隐式调用 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 更新后变量被删除,所以我也删除了我的解决方法。