How can I clear the terminal screen in Go?

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

How can I clear the terminal screen in Go?

问题

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

  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. "github.com/inancgumus/screen"
  6. )
  7. func main() {
  8. for i := 0; i < 10; i++ {
  9. screen.Clear()
  10. screen.MoveTopLeft()
  11. fmt.Println("Clearing the screen...")
  12. time.Sleep(time.Second)
  13. }
  14. }

这段代码使用了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

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

  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. "os/exec"
  6. "runtime"
  7. "time"
  8. )
  9. var clear map[string]func() //创建一个用于存储清屏函数的映射
  10. func init() {
  11. clear = make(map[string]func()) //初始化映射
  12. clear["linux"] = func() {
  13. cmd := exec.Command("clear") //Linux示例,已测试
  14. cmd.Stdout = os.Stdout
  15. cmd.Run()
  16. }
  17. clear["windows"] = func() {
  18. cmd := exec.Command("cmd", "/c", "cls") //Windows示例,已测试
  19. cmd.Stdout = os.Stdout
  20. cmd.Run()
  21. }
  22. }
  23. func CallClear() {
  24. value, ok := clear[runtime.GOOS] //runtime.GOOS -> linux, windows, darwin等
  25. if ok { //如果我们为该平台定义了清屏函数:
  26. value() //执行清屏函数
  27. } else { //不支持的平台
  28. panic("您的平台不受支持!无法清除终端屏幕 :(")
  29. }
  30. }
  31. func main() {
  32. fmt.Println("我将在2秒后清屏!")
  33. time.Sleep(2 * time.Second)
  34. CallClear()
  35. fmt.Println("我很孤单...")
  36. }

(命令执行来自@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

  1. package main
  2. import (
  3. &quot;fmt&quot;
  4. &quot;os&quot;
  5. &quot;os/exec&quot;
  6. &quot;runtime&quot;
  7. &quot;time&quot;
  8. )
  9. var clear map[string]func() //create a map for storing clear funcs
  10. func init() {
  11. clear = make(map[string]func()) //Initialize it
  12. clear[&quot;linux&quot;] = func() {
  13. cmd := exec.Command(&quot;clear&quot;) //Linux example, its tested
  14. cmd.Stdout = os.Stdout
  15. cmd.Run()
  16. }
  17. clear[&quot;windows&quot;] = func() {
  18. cmd := exec.Command(&quot;cmd&quot;, &quot;/c&quot;, &quot;cls&quot;) //Windows example, its tested
  19. cmd.Stdout = os.Stdout
  20. cmd.Run()
  21. }
  22. }
  23. func CallClear() {
  24. value, ok := clear[runtime.GOOS] //runtime.GOOS -&gt; linux, windows, darwin etc.
  25. if ok { //if we defined a clear func for that platform:
  26. value() //we execute it
  27. } else { //unsupported platform
  28. panic(&quot;Your platform is unsupported! I can&#39;t clear terminal screen :(&quot;)
  29. }
  30. }
  31. func main() {
  32. fmt.Println(&quot;I will clean the screen in 2 seconds!&quot;)
  33. time.Sleep(2 * time.Second)
  34. CallClear()
  35. fmt.Println(&quot;I&#39;m alone...&quot;)
  36. }

(the command execution is from @merosss' answer)

答案2

得分: 67

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

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

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

英文:

You could do it with ANSI escape codes:

  1. 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等系统上运行。

按照以下方式安装它:

  1. go get github.com/inancgumus/screen

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

  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. "github.com/inancgumus/screen"
  6. )
  7. func main() {
  8. // 清屏
  9. screen.Clear()
  10. for {
  11. // 将光标移动到屏幕左上角
  12. screen.MoveTopLeft()
  13. fmt.Println(time.Now())
  14. time.Sleep(time.Second)
  15. }
  16. }
英文:

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:

  1. go get github.com/inancgumus/screen

Then you can use it like so:

  1. package main
  2. import (
  3. &quot;fmt&quot;
  4. &quot;time&quot;
  5. &quot;github.com/inancgumus/screen&quot;
  6. )
  7. func main() {
  8. // Clears the screen
  9. screen.Clear()
  10. for {
  11. // Moves the cursor to the top left corner of the screen
  12. screen.MoveTopLeft()
  13. fmt.Println(time.Now())
  14. time.Sleep(time.Second)
  15. }
  16. }

答案4

得分: 16

使用 goterm

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

Use goterm

  1. package main
  2. import (
  3. tm &quot;github.com/buger/goterm&quot;
  4. &quot;time&quot;
  5. )
  6. func main() {
  7. tm.Clear() // Clear current screen
  8. for {
  9. // By moving cursor to top-left position we ensure that console output
  10. // will be overwritten each time, instead of adding new.
  11. tm.MoveCursor(1, 1)
  12. tm.Println(&quot;Current Time:&quot;, time.Now().Format(time.RFC1123))
  13. tm.Flush() // Call it every time at the end of rendering
  14. time.Sleep(time.Second)
  15. }
  16. }

答案5

得分: 10

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

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

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

英文:

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

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

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

答案6

得分: 4

以下是翻译好的内容:

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

  1. fmt.Println("3[2J")

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

英文:

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

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

答案7

得分: 2

这是一个简洁的方法:

  1. package util
  2. import (
  3. "os"
  4. "os/exec"
  5. "runtime"
  6. )
  7. func runCmd(name string, arg ...string) {
  8. cmd := exec.Command(name, arg...)
  9. cmd.Stdout = os.Stdout
  10. cmd.Run()
  11. }
  12. func ClearTerminal() {
  13. switch runtime.GOOS {
  14. case "darwin":
  15. runCmd("clear")
  16. case "linux":
  17. runCmd("clear")
  18. case "windows":
  19. runCmd("cmd", "/c", "cls")
  20. default:
  21. runCmd("clear")
  22. }
  23. }

希望对你有帮助!

英文:

Here's a concise way of doing it:

  1. package util
  2. import (
  3. &quot;os&quot;
  4. &quot;os/exec&quot;
  5. &quot;runtime&quot;
  6. )
  7. func runCmd(name string, arg ...string) {
  8. cmd := exec.Command(name, arg...)
  9. cmd.Stdout = os.Stdout
  10. cmd.Run()
  11. }
  12. func ClearTerminal() {
  13. switch runtime.GOOS {
  14. case &quot;darwin&quot;:
  15. runCmd(&quot;clear&quot;)
  16. case &quot;linux&quot;:
  17. runCmd(&quot;clear&quot;)
  18. case &quot;windows&quot;:
  19. runCmd(&quot;cmd&quot;, &quot;/c&quot;, &quot;cls&quot;)
  20. default:
  21. runCmd(&quot;clear&quot;)
  22. }
  23. }

答案8

得分: 0

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

  1. 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:

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

答案9

得分: 0

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

  1. package main
  2. import (
  3. "github.com/MasterDimmy/go-cls"
  4. )
  5. func main() {
  6. cls.CLS()
  7. }

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

英文:

Shortest code for Windows and Linux is:

  1. package main
  2. import (
  3. &quot;github.com/MasterDimmy/go-cls&quot;
  4. )
  5. func main() {
  6. cls.CLS()
  7. }

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:

确定