How can I clear the terminal screen in Go?

醉酒当歌 提交于 2019-11-28 19:07:24
mraron

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...")
}

(the command execution is from @merosss' answer)

You could do it with ANSI escape codes:

print("\033[H\033[2J")

But you should know that there is no bulletproof cross-platform solution for such task. You should check platform (Windows / UNIX) and use cls / clear or escape codes.

Use 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)
    }
}

As reported here you can use the following three lines to clear the screen:

c := exec.Command("clear")
c.Stdout = os.Stdout
c.Run()

Don't forget to import "os" and "os/exec".

Don't use command execution for this.

Instead, I've also created a small utility package. It works on Windows and Bash command prompts.

👉https://github.com/inancgumus/screen

package main

import (
    "fmt"
    "time"
    "github.com/inancgumus/screen"
)

func main() {
    // Clears the screen
    screen.Clear()

    for {
        // Moves the cursor to the top left corner of the screen
        screen.MoveTopLeft()

        fmt.Println(time.Now())
        time.Sleep(time.Second)
    }
}

Easy for nix systems:

fmt.Println("\033[2J")
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!