问题内容
每当我在 windows cmd 上的 go 中运行 fmt.print("\033c") 时,它不会清除屏幕,但每当我在 javascript 中执行 console.log("\033c") 时都会打印 c ,它工作正常。 p>
根据以下链接,这应该有效: https://en.wikipedia.org/wiki/ansi_escape_code#windows
https://learn.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences#samples
我尝试在javascript中记录它,它工作正常我还尝试在打印 c 的末尾添加一个 \n 字符,并将其更改为 \x1bc ,它也刚刚打印:c
以下所有打印内容:windows cmd 上的 c
func main() {
fmt.Print("\033c")
fmt.Print("\033c\n")
fmt.Print("\x1bc")
fmt.Print("\x1bc\n")
fmt.Println("\033c")
fmt.Println("\x1bc")
}
我预计它会像 javascript 一样清除屏幕,但由于某种原因它不会
为了澄清我所说的是 ansi 转义码不起作用。
解决方案
问题是 windows 需要 enable_virtual_terminal_processing(0x0004) 控制台标志,我通过使用以下代码将该标志添加到控制台来修复它:
package main
// #include "Windows.h"
import "C"
import "fmt"
func main() {
// Needed for getting handle and getting current console mode
var mode C.DWORD
handle := C.GetStdHandle(C.STD_OUTPUT_HANDLE)
C.GetConsoleMode(handle, &mode)
// Enable Virtual Terminal Processing by adding the flag to the current mode
C.SetConsoleMode(handle, mode|0x0004)
fmt.Print("\033c")
}
===编辑===
就像matmarbon在评论中提到的// #include "windows.h"行是必要的,你需要安装gcc
文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《Golang fmt.Print(“\033c”) 和 fmt.Print(“\x1bc”) 无法清屏(ANSI Escape 代码不起作用)如何修复?》文章吧,也可关注公众号了解相关技术文章。