本文介绍了如何清除Go中的终端屏幕?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我运行GO脚本时,Golang中是否有任何标准方法来清除终端屏幕?或者我必须使用其他一些库?
Are there any standard method in Golang to clear the terminal screen when I run a GO script? or I have to use some other libraries?
推荐答案
您必须为每个不同的操作系统定义一个清晰的方法,就像这样。当用户的操作系统不被支持时,它恐慌
You have to define a clear method for every different OS, like this. When the user's os is unsupported it panics
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...")
}
(命令执行来自@merosss'answer)
(the command execution is from @merosss' answer)
这篇关于如何清除Go中的终端屏幕?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!