cobra如何主动退出
Cobra 是一个命令行工具库,它本身无法主动退出。但是,你可以在你的应用程序中使用 os.Exit() 函数来退出应用程序,例如:
package main
import (
"fmt"
"os"
"github.com/spf13/cobra"
)
func main() {
rootCmd := &cobra.Command{
Use: "example",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("Hello, World!")
os.Exit(0)
},
}
if err := rootCmd.Execute(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
在上面的例子中,当 rootCmd 执行完毕后,我们使用 os.Exit(0) 退出应用程序。如果你想退出应用程序并返回一个错误代码,可以使用 os.Exit(1)
原文地址: http://www.cveoy.top/t/topic/fuWN 著作权归作者所有。请勿转载和采集!