如何在终端中“清除滚动回溯(也称为“保存的行”)”

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

How to `Erase the scroll-back (aka "Saved Lines")` in the terminal

问题

如何使用Go语言清除终端的滚动缓冲区?

在OS X上使用Terminal,我可以运行以下命令:

$ print '\e[3J'

它将“清除滚动缓冲区(也称为'保存的行')”。很好!

但是,在Go语言中,当我运行以下命令时:

exec.Command("print", `\e[3J`).CombinedOutput()

我收到了错误消息exec: "print": 在$PATH中找不到可执行文件,这是有道理的:

$ type -a print
print是一个shell内置命令

Slack中的热心的Gophers提到我应该研究如何直接与终端应用程序进行通信(无论是Terminal、iTerm还是iTerm2等)。然而,即使在查看了这个链接之后,我仍然感到困惑:https://www.iterm2.com/documentation-scripting.html

英文:

How can I erase the scroll-back in a terminal using Go?

In OS X using Terminal, I can run:

$ print '\e[3J'

and it will "Erase the scroll-back (aka 'Saved Lines')." Great!

But, in Go, when I run:

exec.Command("print", `\e[3J`).CombinedOutput() 

I get the error that exec: "print": executable file not found in $PATH, which makes sense:

$ type -a print
print is a shell builtin

The helpful Gophers in Slack mentioned I should look into communicating the the terminal app directly (whether it be Terminal, iTerm, iTerm2, etc.). However, I'm at a loss even after looking at this: https://www.iterm2.com/documentation-scripting.html

答案1

得分: 2

fmt.Printf(string([]byte{0x1b,'[', '3', 'J'}))

应该足够了。但是你真的应该使用一个终端库,它根据使用的终端仿真器知道要使用哪些代码。

类似于 termbox-go

对于通常可用的代码及其字节值,你可以尝试 xterm-docu,但是你使用不同的终端仿真器时可能会有所不同。

英文:
fmt.Printf(string([]byte{0x1b,'[', '3', 'J'}))

should suffice. But you really should use a terminal library, which knows which codes to use depending on the terminal emulator in use.

Something like termbox-go.

For the usually available codes and their byte values, you can
try xterm-docu but your
mileage may vary, as you use different terminal emulators.

答案2

得分: 2

print 是一个内置的 shell 命令,因此无法从 Go 中执行。你可以使用 /bin/echo 二进制文件、/usr/bin/clear 命令,或者直接使用 fmt.Println 函数来输出转义序列:

seq := "\x1b\x5b\x48"

// 选项 1
out, _ := exec.Command("/bin/echo", seq).Output()
fmt.Println(string(out))

// 选项 2
out, _ := exec.Command("/usr/bin/clear").Output()
fmt.Println(string(out))

// 选项 3(推荐)
fmt.Println(seq)
英文:

print is a shell builtin, so it cannot be executed from go. You could use the /bin/echo binary, /usr/bin/clear, or just fmt.Println the escape sequence:

seq := "\x1b\x5b\x48"

// option 1
out, _ := exec.Command("/bin/echo", seq).Output()
fmt.Println(string(out))

// option 2
out, _ := exec.Command("/usr/bin/clear").Output()
fmt.Println(string(out))

// option 3 (prefered)
fmt.Println(seq)

huangapple
  • 本文由 发表于 2017年7月14日 23:41:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/45106922.html
匿名

发表评论

匿名网友

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

确定