du4373 2018-03-09 05:07
浏览 92

如何在应用程序中丢弃在导入的第三方程序包中定义的标志

Consider, my application uses a third party library. I want my application to accept only the flags defined in my application and not the flags defined in imported packages.

package main

import (
    "flag"
    "fmt"
    log "github.com/golang/glog"
)

var myFlag int

func init() {
    flag.IntVar(&myFlag, "my_flag", 0, "need only my flags")
    confDir := "/Users/foo/test/logs" //assume this is read from configuration file
    flag.Set("log_dir", confDir)
    flag.Parse()
}

func main() {
    flag.Parse()
    log.Errorln("flag", myFlag)
    log.V(0).Infoln("flag", myFlag)
    fmt.Println("test", myFlag)
}

In above code sample, log package has many flags. After compiling when I execute following command, all flags including "my_flag" and flags from log package are displayed. But, I want to set the values for log package flags from my code with values obtained from configuration file.

  -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
  -my_flag int
        need only my flags
  -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

How to restrict my application executable from accepting other flags?

  • 写回答

2条回答 默认 最新

  • douliao8318 2018-03-09 06:57
    关注

    If you want to discard the flags of other packages, then you can use a new flagset instead of the default one.

    package main
    
    import (
        "flag"
        "fmt"
        "os"
    )
    
    var myFlag int
    
    func main() {
        f := flag.NewFlagSet(os.Args[0], flag.ExitOnError)
        f.IntVar(&myFlag, "my_flag", 0, "need only my flags")
        confDir := "/Users/foo/test/logs" //assume this is read from configuration file
        f.Set("log_dir", confDir)
        f.Parse(os.Args[1:])
        fmt.Println("test", myFlag)
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图