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

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

问题描述

Windows 10的最新更新包括



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



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

 >> import sys 
>> sys.stdout.write( \033 [?25l)

嗯,游标是t隐藏。如何设置正确的方式,以便控制台能够从Python获取转义序列?

解决方案

问题是Python解释器无法启用ANSI转义序列的处理。 ANSI序列在Windows命令提示符下工作,因为 cmd 确实启用了它们。如果您从命令提示符处启动Python,您会发现ANSI序列可以正常工作,包括用于启用和禁用光标的序列。这是因为 cmd 已经在控制台窗口中启用了它们。



如果您想要一些东西,可以单击在启用ANSI转义的情况下启动Python解释器,您可以创建一个运行 cmd / c C:\PythonXY\python 之类的命令的快捷方式。



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

  import ctypes 

kernel32 = ctypes.windll.kernel32
kernel32。 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("\033[?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:\PythonXY\python.

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天全站免登陆