我将 Python 安装从 3.4 更新到 3.5(Windows 7 Enterprise 64 位上的 CPython 64 位)。之后更新 colorama 停止将 ANSI 转义序列转换为 Win32 API 调用以更改命令行终端颜色。
需要显式的 colorama.init(convert=True)
才能获得彩色输出。我试图缩小错误范围:
- 自 Python 3.5 更新以来就出现了
- 如果我使用转换选项隐式调用
init()
,则可以解决此问题。 - 从 cmd.exe 启动彩色 Python 脚本可以正常工作。
- 从 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 更新后,变量被删除,所以我也删除了我的解决方法。
关于Python 3.5 : Colorama does not recognize Windows environment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33698866/