How can I clear the terminal screen in Go?

huangapple go评论77阅读模式
英文:

How can I clear the terminal screen in Go?

问题

在Golang中,没有标准的方法来清除终端屏幕。但你可以使用第三方库来实现这个功能。一个常用的库是github.com/inancgumus/screen,它提供了清除终端屏幕的函数。你可以使用该库来清除屏幕,例如:

package main

import (
	"fmt"
	"time"

	"github.com/inancgumus/screen"
)

func main() {
	for i := 0; i < 10; i++ {
		screen.Clear()
		screen.MoveTopLeft()
		fmt.Println("Clearing the screen...")
		time.Sleep(time.Second)
	}
}

这段代码使用了screen库来清除终端屏幕,并在屏幕上打印一条消息。你可以根据需要自定义清除屏幕的逻辑。

英文:

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?

答案1

得分: 74

你需要为每个不同的操作系统定义一个清屏方法,如下所示。当用户的操作系统不受支持时,它会引发错误。

package main

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

var clear map[string]func() //创建一个用于存储清屏函数的映射

func init() {
	clear = make(map[string]func()) //初始化映射
	clear["linux"] = func() {
		cmd := exec.Command("clear") //Linux示例,已测试
		cmd.Stdout = os.Stdout
		cmd.Run()
	}
	clear["windows"] = func() {
		cmd := exec.Command("cmd", "/c", "cls") //Windows示例,已测试
		cmd.Stdout = os.Stdout
		cmd.Run()
	}
}

func CallClear() {
	value, ok := clear[runtime.GOOS] //runtime.GOOS -> linux, windows, darwin等
	if ok { //如果我们为该平台定义了清屏函数:
		value() //执行清屏函数
	} else { //不支持的平台
		panic("您的平台不受支持!无法清除终端屏幕 :(")
	}
}

func main() {
	fmt.Println("我将在2秒后清屏!")
	time.Sleep(2 * time.Second)
	CallClear()
	fmt.Println("我很孤单...")
}

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

英文:

Note: Running a command to clear the screen is not a secure way. Check the other answers here as well.


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 (
	&quot;fmt&quot;
	&quot;os&quot;
	&quot;os/exec&quot;
	&quot;runtime&quot;
	&quot;time&quot;
)

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

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

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

func main() {
	fmt.Println(&quot;I will clean the screen in 2 seconds!&quot;)
	time.Sleep(2 * time.Second)
	CallClear()
	fmt.Println(&quot;I&#39;m alone...&quot;)
}

(the command execution is from @merosss' answer)

答案2

得分: 67

你可以使用ANSI转义码来实现:

fmt.Print("3[H3[2J")

但是你应该知道,没有一个完全可靠的跨平台解决方案来完成这个任务。你应该检查平台(Windows / UNIX)并使用cls / clear或转义码。

英文:

You could do it with ANSI escape codes:

fmt.Print(&quot;3[H3[2J&quot;)

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.

答案3

得分: 17

不要使用命令执行来完成这个任务。这样做过于复杂,不能保证可行,并且不安全。


我创建了一个小型的跨平台包,因此它可以在Windows、Linux、OS X等系统上运行。

按照以下方式安装它:

go get github.com/inancgumus/screen

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

package main

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

func main() {
    // 清屏
    screen.Clear()

    for {
        // 将光标移动到屏幕左上角
        screen.MoveTopLeft()

        fmt.Println(time.Now())
        time.Sleep(time.Second)
    }
}
英文:

Don't use command execution for this. It's overkill, and not guaranteed to work, and it's not secure.


I created a small cross-platform package. So it works on Windows, Linux, OS X, etc.

Install it like this:

go get github.com/inancgumus/screen

Then you can use it like so:

package main

import (
    &quot;fmt&quot;
    &quot;time&quot;
    &quot;github.com/inancgumus/screen&quot;
)

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

答案4

得分: 16

使用 goterm

package main

import (
    tm "github.com/buger/goterm"
    "time"
)
func main() {
    tm.Clear() // 清除当前屏幕
    for {
        // 将光标移动到左上角位置,确保控制台输出每次都会被覆盖,而不是添加新的内容。
        tm.MoveCursor(1, 1)
        tm.Println("当前时间:", time.Now().Format(time.RFC1123))
        tm.Flush() // 每次渲染结束时都要调用它
        time.Sleep(time.Second)
    }
}
英文:

Use goterm

package main

import (
	tm &quot;github.com/buger/goterm&quot;
	&quot;time&quot;
)
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(&quot;Current Time:&quot;, time.Now().Format(time.RFC1123))
		tm.Flush() // Call it every time at the end of rendering
		time.Sleep(time.Second)
	}
}

答案5

得分: 10

根据这里的报道,你可以使用以下三行代码来清除屏幕:

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

不要忘记导入"os"和"os/exec"。

英文:

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

c := exec.Command(&quot;clear&quot;)
c.Stdout = os.Stdout
c.Run()

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

答案6

得分: 4

以下是翻译好的内容:

仅适用于*nix系统(Linux、Unix等)的简单解决方案:

fmt.Println("3[2J")

这段代码用于清除终端屏幕。

英文:

Easy solution only for nix systems (linux, unix, etc.):

fmt.Println(&quot;3[2J&quot;)

答案7

得分: 2

这是一个简洁的方法:

package util

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

func runCmd(name string, arg ...string) {
	cmd := exec.Command(name, arg...)
	cmd.Stdout = os.Stdout
	cmd.Run()
}

func ClearTerminal() {
	switch runtime.GOOS {
	case "darwin":
		runCmd("clear")
	case "linux":
		runCmd("clear")
	case "windows":
		runCmd("cmd", "/c", "cls")
	default:
		runCmd("clear")
	}
}

希望对你有帮助!

英文:

Here's a concise way of doing it:

package util

import (
	&quot;os&quot;
	&quot;os/exec&quot;
	&quot;runtime&quot;
)

func runCmd(name string, arg ...string) {
	cmd := exec.Command(name, arg...)
	cmd.Stdout = os.Stdout
	cmd.Run()
}

func ClearTerminal() {
	switch runtime.GOOS {
	case &quot;darwin&quot;:
		runCmd(&quot;clear&quot;)
	case &quot;linux&quot;:
		runCmd(&quot;clear&quot;)
	case &quot;windows&quot;:
		runCmd(&quot;cmd&quot;, &quot;/c&quot;, &quot;cls&quot;)
	default:
		runCmd(&quot;clear&quot;)
	}
}

答案8

得分: 0

对于我来说(在我的手机上在termux上测试),这个代码可以工作:

os.Stdout.Write([]byte{0x1B, 0x5B, 0x33, 0x3B, 0x4A, 0x1B, 0x5B, 0x48, 0x1B, 0x5B, 0x32, 0x4A})
英文:

For me (tested on my mobile phone in termux) this works:

os.Stdout.Write([]byte{0x1B, 0x5B, 0x33, 0x3B, 0x4A, 0x1B, 0x5B, 0x48, 0x1B, 0x5B, 0x32, 0x4A})

答案9

得分: 0

以下是Windows和Linux的最短代码:

package main

import (
    "github.com/MasterDimmy/go-cls"
)

func main() {
    cls.CLS()
}

这段代码使用了 go-cls 包来清除终端屏幕。

英文:

Shortest code for Windows and Linux is:

package main

import (
 &quot;github.com/MasterDimmy/go-cls&quot;
)
func main() {
 cls.CLS()
}

huangapple
  • 本文由 发表于 2014年4月6日 16:27:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/22891644.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定