运行GO脚本时,Golang中是否有任何标准方法可以清除终端屏幕?还是我必须使用其他一些库?
注意: 运行命令以清除屏幕不是安全的方法。在这里也检查其他答案。
您必须为每个不同的OS定义一个清晰的方法,像这样。当用户的操作系统不受支持时,它会慌乱
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的答案)