doujiang6944 2015-01-22 15:03
浏览 45
已采纳

Golang标志库:无法覆盖打印命令行用法的用法功能

I am working on a simple command line tool and I found the default Usage message a bit lacking. I want to define my own and I think I am doing it right I am referring to this example.

I commented out most of the code I had written so the file containing the main function now looks like this:

package main

import (
    "flag"
    "fmt"
    "os"
)

func main() {
    // set the custom Usage function
    setupFlags(flag.CommandLine)
    // define flags...
    // then parse flags
    flag.Parse()
    // custom code that uses flag values...
}

func setupFlags(f *flag.FlagSet) {
    f.Usage = func() {
        fmt.Println("foo bar")
    }
}

It seems like this should work, but it doesn't. When running <binary> -h I get the default usage message and not my custom foo bar message that I defined in my custom function. I am using Go version 1.3.3 on OSX. I found this commit but it is for Go 1.4rc2.

What am I doing wrong?

  • 写回答

1条回答 默认 最新

  • douxiongye5779 2015-01-22 15:08
    关注

    Edit:

    Actually revisiting your code it works! What version of Go are you using? Maybe you need to rebuild your code.

    The decision of what Usage function to call is in the flag.go source file, line 708, unexported function usage() (this is from Go 1.4):

    func (f *FlagSet) usage() {
        if f.Usage == nil {
            if f == CommandLine {
                Usage()
            } else {
                defaultUsage(f)
            }
        } else {
            f.Usage()
        }
    }
    

    This tells if the FlagSet.Usage is not nil, it will be called. If it is not called for you, it's most likely you're using a Go version prior to 1.4 (which you confirmed in your comment).

    But since you're using the default flag.CommandLine flagset, you can simply write:

    // Note "flag.Usage" instead of "f.Usage"
    
    flag.Usage = func() {
        fmt.Println("foo bar")
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探