How can I clear the console with golang in windows?

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

How can I clear the console with golang in windows?

问题

我已经尝试了很多方法,比如:

package main
import (
    "os"
    "os/exec"
)

func main() {
    c := exec.Command("cls")
    c.Stdout = os.Stdout
    c.Run()
}

C.system(C.CString("cls"))

但转义序列也不起作用。

英文:

I've tried a lot of ways, like

package main 
import (
    "os"
    "os/exec"
)

func main() {
    c := exec.Command("cls")
    c.Stdout = os.Stdout
    c.Run()
}

and

C.system(C.CString("cls"))

And the escape sequence doesn't work either

答案1

得分: 12

你需要的是:

package main

import (
	"os"
	"os/exec"
)

func main() {
	cmd := exec.Command("cmd", "/c", "cls")
	cmd.Stdout = os.Stdout
	cmd.Run()
}

这是一个使用Go语言编写的程序,它使用os/exec包来执行命令行指令。该程序会调用Windows系统的命令行(cmd.exe)并执行cls命令,用于清空命令行窗口的内容。

英文:

All you need is :

package main

import (
"os"
"os/exec"
)

func main() {
	cmd := exec.Command("cmd", "/c", "cls")
	cmd.Stdout = os.Stdout
	cmd.Run()
}

答案2

得分: 11

使用标准库在跨平台的方式中,确实没有简单的方法来做到这一点。

termbox-go 似乎是一个提供跨平台终端控制的库。可能还有其他类似的库,但这是我使用过的唯一一个,而且它似乎工作得很好。

使用 termbox-go 清除控制台的方法是调用 Clear 然后调用 Flush

更多详情请参考 http://godoc.org/github.com/nsf/termbox-go

英文:

There's really no easy way to do this in a cross-platform way using the standard libraries.

termbox-go seems to be one library providing cross-platform terminal control. There are probably others, but it's the only one I've used and it seems to work well.

Clearing the console using termbox-go would be a matter of doing a Clear and then a Flush.

See http://godoc.org/github.com/nsf/termbox-go for more details.

答案3

得分: 4

对于Linux和Mac,如果有人需要的话:

fmt.Println("3[2J")

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

英文:

For linux and mac in case someone needs it:

fmt.Println("3[2J")

答案4

得分: 0

如果你查看《康威生命游戏》的游乐场链接,你会看到他们通过特定的指令来清除终端:

// 第110行 fmt.Print("\x0c", l)

英文:

If you look at the playground "Conway's Game of Life", you can see how they clear the terminal by means of a specific instruction:

//line 110
fmt.Print("\x0c", l)

huangapple
  • 本文由 发表于 2013年10月6日 21:33:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/19209425.html
匿名

发表评论

匿名网友

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

确定