如何在 Windows 10 控制台中使用对 ANSI 转义序列的新支持? [英] How to use the new support for ANSI escape sequences in the Windows 10 console?

查看:33
本文介绍了如何在 Windows 10 控制台中使用对 ANSI 转义序列的新支持?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最新的 Windows 10 更新包括

我已经能够确认在 cmd.exe 中正确提取了转义序列,因此我有必要的更新.特别是,我尝试输入 prompt $e[?25l,隐藏光标,然后输入 prompt $e[?25h,再次显示光标.>

但是,如果我启动 Python 解释器,然后执行以下操作:

<预><代码>>>>导入系统>>>sys.stdout.write("33[?25l")

好吧,光标没有隐藏.如何以正确的方式进行设置,以便控制台能够从 Python 获取转义序列?

解决方案

问题是 Python 解释器不支持 ANSI 转义序列的处理.ANSI 序列在 Windows 命令提示符下工作,因为 cmd 确实启用了它们.如果从命令提示符启动 Python,您会发现 ANSI 序列确实有效,包括用于启用和禁用光标的序列.那是因为 cmd 已经为那个控制台窗口启用了它们.

如果你想要一些东西,你可以点击它来启动启用了 ANSI 转义的 Python 解释器,你可以创建一个快捷方式来运行类似 cmd/c C:PythonXYpython 的命令.

另一种更难的解决方案是使用 ctypes 为控制台窗口启用 ANSI 转义序列处理,方法是通过 ENABLE_VIRTUAL_TERMINAL_PROCESSING 标志集.例如:

import ctypeskernel32 = ctypes.windll.kernel32kernel32.SetConsoleMode(kernel32.GetStdHandle(-11), 7)

The latest Windows 10 updates include support for ANSI escape sequences in conhost.exe.

I have been able to confirm that the escape sequences are properly picked up in cmd.exe, so I have the necessary updates. In particular, I tried typing in prompt $e[?25l, which hides the cursor, and then prompt $e[?25h, which again shows the cursor.

However, if I start a Python interpreter, and then do the following:

>>> import sys
>>> sys.stdout.write("33[?25l")

Well, the cursor isn't hidden. How can I set things up the right way so that the console is able to get escape sequences from Python?

解决方案

The problem is that the Python interpreter doesn't enable the processing of ANSI escape sequences. The ANSI sequences work from the Windows command prompt because cmd does enable them. If you start Python from the command prompt you'll find the ANSI sequences do work, including the ones for enabling and disabling the cursor. That's because cmd has already enabled them for that console window.

If you want have something you can click on to start the Python interpreter with ANSI escapes enabled you can create a shortcut that runs a command something like cmd /c C:PythonXYpython.

Another, harder, solution would be to use ctypes to enable ANSI escape sequence processing for the console window by calling the SetConsoleMode Windows API with the ENABLE_VIRTUAL_TERMINAL_PROCESSING flag set. For example:

import ctypes

kernel32 = ctypes.windll.kernel32
kernel32.SetConsoleMode(kernel32.GetStdHandle(-11), 7)

这篇关于如何在 Windows 10 控制台中使用对 ANSI 转义序列的新支持?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆