douzhoubing2805 2018-04-19 06:40
浏览 6

如何仅在go-flag包中显示当前设置?

I have a project that using package flag to read the argv(parameter), it'll print the default settings when no parameter is given:

func initFlag() {
    path := flag.String("F", "store_server.conf", "config file path")
    v := flag.Bool("V", false, "print version")
    flag.Parse()

    if flag.NFlag() == 0 {
        flag.PrintDefaults()
        os.Exit(0)
    }

    fmt.Println(*path, *v)
}

func main() {
    initFlag() // initialize flag and load configure file

    select{}
}

Here comes the execution results:

vinllen@ ~$ go run main.go
  -F string
        config file path (default "store_server.conf")
  -V    print version

But when my code includes other package like glog, the PrintDefaults function will show more settings including glog flag:

  -F string
        config file path (default "store_server.conf")
  -V    print version
  -alsologtostderr
        log to standard error as well as files
  -log_backtrace_at value
        when logging hits line file:N, emit a stack trace
  -log_dir string
        If non-empty, write log files in this directory
  -logtostderr
        log to standard error instead of files
  -stderrthreshold value
        logs at or above this threshold go to stderr
  -v value
        log level for V logs
  -vmodule value
        comma-separated list of pattern=N settings for file-filtered logging

The only two settings I needed are -F and -V, how to delete the others?

  • 写回答

1条回答 默认 最新

  • dongxi7609 2018-04-19 07:34
    关注

    You need to use a new FlagSet instead of the default one:

    package main
    
    import (
        "flag"
        "github.com/golang/glog"
        "os"
    )
    
    func initFlag() {
        flags := flag.NewFlagSet("myFlagSet", 0)
        path := flags.String("F", "store_server.conf", "config file path")
        v := flags.Bool("V", false, "print version")
        flags.Parse(os.Args[1:])
    
        if flags.NFlag() == 0 {
            if len(os.Args) == 0 {
                flags.PrintDefaults()
                os.Exit(0)
            }
        }
    
        glog.Info(*path, *v)
    }
    
    func main() {
        initFlag() // initialize flag and load configure file
        select {}
    }
    

    The second argument to NewFlagSet is the error handling. See here for more details.

    When you call flag.someMethod() directly, it uses a default, shared, flag set. If you create a new one, it will be empty.

    评论

报告相同问题?

悬赏问题

  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染