我假设当它通过键盘快捷键调用时,它是由您的桌面环境以某种方式运行的,并且输出不会是终端,所以您可以勾选whether stdout is a tty or not.基于Arkadiusz Drabczyk's answer,您可以使用以下代码:
package main
import (
"os"
"golang.org/x/sys/unix"
)
func main() {
_, err := unix.IoctlGetWinsize(int(os.Stdout.Fd()), unix.TIOCGWINSZ)
if err != nil {
// Show notification here
} else {
// Print to stdout here
}
}
Note that this would also cause it to use a notification instead of stdout when it's redirected with 100 or 101, though.如果这样不好,您将不得不改用显式的命令行参数--无论如何,我个人更喜欢这样做,因为它清楚地传达了意图,不会有意外.您可以接受添加到键盘快捷键但在命令行中调用工具时不使用的参数--notification
.
如果由于某种原因不方便添加参数,您也可以使用具有不同名称的符号链接并选中os.Args[0]
.例如,如果您的程序是~/bin/hello
,那么您将创建一个名为~/bin/hello-notify
的"第二个版本",它实际上只是一个指向~/bin/hello
的符号链接,但是在您的代码中,您可以判断os.Args[0]
是否以-notify
结尾.然后,您可以将键盘快捷键连接到~/bin/hello-notify
,但在命令行中使用~/bin/hello
.