如何在Go中清除终端屏幕?

Ani*_*hah 42 go

当我运行GO脚本时,Golang中是否有任何标准方法可以清除终端屏幕?或者我必须使用其他一些图书馆?

mra*_*ron 47

您必须为每个不同的操作系统定义一个清晰的方法,如下所示.当用户的操作系统不受支持时,它会发生恐慌

package main

import (
    "fmt"
    "os"
    "os/exec"
    "runtime"
    "time"
)

var clear map[string]func() //create a map for storing clear funcs

func init() {
    clear = make(map[string]func()) //Initialize it
    clear["linux"] = func() { 
        cmd := exec.Command("clear") //Linux example, its tested
        cmd.Stdout = os.Stdout
        cmd.Run()
    }
    clear["windows"] = func() {
        cmd := exec.Command("cmd", "/c", "cls") //Windows example, its tested 
        cmd.Stdout = os.Stdout
        cmd.Run()
    }
}

func CallClear() {
    value, ok := clear[runtime.GOOS] //runtime.GOOS -> linux, windows, darwin etc.
    if ok { //if we defined a clear func for that platform:
        value()  //we execute it
    } else { //unsupported platform
        panic("Your platform is unsupported! I can't clear terminal screen :(")
    }
}

func main() {
    fmt.Println("I will clean the screen in 2 seconds!")
    time.Sleep(2 * time.Second)
    CallClear()
    fmt.Println("I'm alone...")
}
Run Code Online (Sandbox Code Playgroud)

(命令执行来自@merosss'回答)

  • 这适用于Windows:`cmd:= exec.Command("cmd","/ c","cls")` (3认同)

Kav*_*avu 26

您可以使用ANSI转义码来执行此操作:

print("\033[H\033[2J")
Run Code Online (Sandbox Code Playgroud)

但是你应该知道没有针对此类任务的防弹跨平台解决方案.您应该检查平台(Windows/UNIX)并使用cls/ clear或转义码.


Kas*_*kal 12

使用goterm

package main

import (
    tm "github.com/buger/goterm"
    "time"
)
func main() {
    tm.Clear() // Clear current screen
    for {
        // By moving cursor to top-left position we ensure that console output
        // will be overwritten each time, instead of adding new.
        tm.MoveCursor(1, 1)
        tm.Println("Current Time:", time.Now().Format(time.RFC1123))
        tm.Flush() // Call it every time at the end of rendering
        time.Sleep(time.Second)
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 查看goterm的来源,它使用与[Kavu的答案](/sf/answers/1602452001/)相同的解决方案。 (2认同)

Ina*_*mus 9

不要为此使用命令执行。这是矫枉过正,不能保证工作,而且不安全。


我创建了一个小的跨平台包。所以它适用于 Windows、Linux、OS X 等。

像这样安装它:

go get https://github.com/inancgumus/screen
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样使用它:

go get https://github.com/inancgumus/screen
Run Code Online (Sandbox Code Playgroud)


mer*_*sss 6

如此处所报告您可以使用以下三行清除屏幕:

c := exec.Command("clear")
c.Stdout = os.Stdout
c.Run()
Run Code Online (Sandbox Code Playgroud)

不要忘记导入“ os”和“ os / exec”。

  • 否,我刚刚检查了一下,在cmd.exe上无法识别“清除”。(是“ cls”) (2认同)