[英]Why do ANSI escape codes sometimes work in CMD
ANSI escape codes do not work by default in cmd. ANSI 转义码在 cmd 中默认不起作用。
But however some application do some kind of initialization after which they seem to seem to work during that session.但是,一些应用程序进行了某种初始化,之后它们似乎在 session 期间工作。
How do they do this initialization?他们如何进行初始化? Here is an example -
这是一个例子 -
I built a simple rust application that uses ANSI codes for colorful output.我构建了一个简单的 rust 应用程序,它使用彩色 output 的 ANSI 代码。
However if I first build the project, then close that session and then again start cmd going to the directory in which my compiled project is and then run the executable (this time without using cargo at all in this session)-但是,如果我首先构建项目,然后关闭 session,然后再次启动 cmd,转到我编译的项目所在的目录,然后运行可执行文件(这次在此会话中根本不使用货物)-
It seems like applications like cargo (and other applications also) do some kind of initialization step in the cmd after which the terminal seems to recognize ANSI codes.似乎像 cargo(以及其他应用程序)这样的应用程序在 cmd 中执行了某种初始化步骤,之后终端似乎可以识别 ANSI 代码。
And also in Python Calling os.system('')
before using ANSIescape codes does the job -并且还在 Python 中调用
os.system('')
在使用 ANSIescape 代码之前调用 -
It seems like os.system('')
is a bug, and you shoudn't rely on bugs to make your code work.似乎
os.system('')
是一个错误,您不应该依赖错误来使您的代码正常工作。 Is there a better way to initialize ANSI escape codes in cmd?有没有更好的方法来初始化 cmd 中的 ANSI 转义码?
What you're searching for isENABLE_VIRTUAL_TERMINAL_PROCESSING
.您要搜索的是
ENABLE_VIRTUAL_TERMINAL_PROCESSING
。 The reason it sometimes "stops working", is because some applications disable it before exiting.它有时“停止工作”的原因是因为某些应用程序在退出之前将其禁用。 If it was already enabled, then this is when stuff breaks.
如果它已经启用,那么这就是东西中断的时候。
However, you can easily enable it (again) by calling SetConsoleMode()
using the winapi
crate .但是,您可以通过使用
winapi
crate调用SetConsoleMode()
轻松启用它(再次)。 You can also use the winapi-util
crate which makes it a bit easier.你也可以使用
winapi-util
crate ,这让它更容易一些。
#[cfg(windows)]
pub fn enable_virtual_terminal_processing() {
use winapi_util::console::Console;
if let Ok(mut term) = Console::stdout() {
let _ = term.set_virtual_terminal_processing(true);
}
if let Ok(mut term) = Console::stderr() {
let _ = term.set_virtual_terminal_processing(true);
}
}
[target.'cfg(windows)'.dependencies]
winapi-util = "0.1"
To be safe you could call enable_virtual_terminal_processing()
initially in main()
.为了安全起见,您最初可以在
main()
中调用enable_virtual_terminal_processing()
) 。 However, I definitely recommend calling it after executing astd::process::Command
, eg:但是,我绝对建议在执行
std::process::Command
后调用它,例如:
let output = Command::new("...")
.args(&["..."])
.output()
.expect("failed to execute process");
#[cfg(windows)]
enable_virtual_terminal_processing();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.