我使用 cobra 創(chuàng)建 CLI 命令工具。除了錯誤處理,一切看起來都很好我想要的是如果錯誤發(fā)送了命令(錯誤的參數(shù)或錯誤的輸入)返回std.err而不是std.out為了簡化 secnario 我創(chuàng)建了這個來演示我的用例package mainimport ( "errors" "fmt" "os" "github.com/spf13/cobra")var ( RootCmd = &cobra.Command{ Use: "myApp", Run: func(cmd *cobra.Command, args []string) { fmt.Printf("ROOT verbose = %d, args = %v\n", args) }, } provideCmd = &cobra.Command{ Use: "provide", Run: nil, } appCmd = &cobra.Command{ Use: "apps", RunE: func(cmd *cobra.Command, args []string) error { name := args[0] if name != "myapp" { err := errors.New("app name doesnt exist") return err } return nil }, SilenceUsage: true, })func init() { // Add the application command to app command provideCmd.AddCommand(appCmd) // add provide command to root command RootCmd.AddCommand(provideCmd)}func main() { if err := RootCmd.Execute(); err != nil { fmt.Println(err) os.Exit(-1) }}現(xiàn)在,如果我編譯二進制文件并exec.Command針對二進制文件運行,一切都會按預期工作。但是如果我想測試錯誤場景就像mycli provide apps apps1 我想看到返回的std.err而不是std.out當我執(zhí)行時,mycli provide apps myapp一切都應該沒問題但是如果我運行mycli provide apps myapp2我想得到 std.err 而不是 std.out ,這里不是這種情況......我在這里錯過了什么?https://play.golang.org/p/B00z4eZ7Sj-
1 回答

慕妹3242003
TA貢獻1824條經(jīng)驗 獲得超6個贊
您的示例已經(jīng)將錯誤打印到stdout
和stderr
。
默認情況下,cobra
包將遇到的任何錯誤打印到stderr
,除非您特別更改它。
所以運行 ./main provide apps something 2> ./stderr.txt
會創(chuàng)建一個包含以下內容的文本文件(這是 cobra 在stderr
沒有您干預的情況下寫入的內容):
Error: app name doesnt exist
并運行./main provide apps something > ./stdout.txt
- 創(chuàng)建一個包含以下內容的文本文件(您自己打印了fmt.Println(err)
,代碼中從底部開始的第二行):
app name doesnt exist
這意味著默認行為會向stdout
和stderr
打印錯誤。
正如 Devin 所建議的那樣,將最后一行更改為os.Stderr.WriteString(err)
or fmt.Fprintln(os.Stderr, err)
(我會使用的那一行)將使您的項目將 所有內容打印到stderr
only,這意味著打印錯誤兩次:
Error: app name doesnt exist app name doesnt exist
了解 cobra 允許您對錯誤打印行為進行一些控制可能會很有用。例如,您可以告訴 cobra 命令要打印到哪個流:
command.SetOutput(os.Stdout) // Defaults to os.Stderr
您還可以防止打印錯誤:
command.SilenceErrors = true
或阻止打印使用文本:
command.SilenceUsage = true
- 1 回答
- 0 關注
- 133 瀏覽
添加回答
舉報
0/150
提交
取消