Golang fmt.Print(“ \ 033c”)和fmt.Print(“ \ x1bc”)无法清除屏幕(ANSI Escape代码不起作用)如何解决?

时间:2019-06-05 12:38:22

标签: windows go cmd ascii command-prompt

每当我在Windows cmd的golang中运行ERROR: Function failed: SYSTEMD_SERVICE_ecdsa value dispatcherd.service does not exist 时,它都不会清除屏幕,但是每当我在javascript中执行devon@VM ~/app/build/tmp-glibc $ find . -name "dispatcherd*.service" ./work/cortexa9hf-vfp-neon-phytec-linux-gnueabi/ecdsa/1.0.0-r0/dispatcherd.service ./work/cortexa9hf-vfp-neon-phytec-linux-gnueabi/ecdsa/1.0.0-r0/package/dispatcherd.service ./work/cortexa9hf-vfp-neon-phytec-linux-gnueabi/ecdsa/1.0.0-r0/image/dispatcherd.service 时,它就会打印fmt.Print("\033c"),效果很好。

根据以下链接,该链接应该已经起作用: https://en.wikipedia.org/wiki/ANSI_escape_code#Windows

https://docs.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences#samples

我尝试将其记录在javascript中,并且工作正常,我还尝试在打印c的末尾添加\ n字符,并将其更改为也刚刚打印过的\ x1bc:console.log("\033c")

以下所有打印:Windows cmd上的c

c

我希望它会像javascript中一样清除屏幕,但由于某种原因它不会

澄清一下,我说的是ANSI escape code无效。

1 个答案:

答案 0 :(得分:1)

问题是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")
}

SetConsoleMode