是否可以覆盖标志值?

huangapple go评论72阅读模式
英文:

Is it possible to overwrite flag values?

问题

我想知道是否可以在运行时覆盖标志值。

示例:

  • main.go 导入了一个名为 pkg.go 的包。
  • pkg.go 使用一个标志("-myFlag"),但存储标志的标识符未被导出。

是否可以更改 main.go 发送给 pkg.go 的 "-myFlag" 标志值?

用例:我正在使用一个库,该库使用 glog 记录错误日志。glog 使用标志来定义日志写入的位置,默认情况下将日志写入文件。我使用的环境不允许写入文件系统,也不允许在应用程序初始化时设置标志,因此我需要以某种方式覆盖/设置 glog 的标志,以便将错误写入 stderr。

英文:

I'm wondering if it's possible to overwrite flag values on runtime.

Example:

  • main.go imports a package pkg.go.
  • pkg.go uses a flag ("-myFlag") but the identifier which stores the flag is not exported.

Is it possible to change the flag value of "-myFlag" which pkg.go receives from main.go ?

Usecase: I'm using a library which uses glog to log the errors. glog uses flags to define where to write the logs and by default it writes the logs to a file. The environment I'm using doesn't allow writes to filesystem nor to set flags on app initialisation so I need to overwrite/set the glog flags somehow so that I can set it to write the errors to stderr.

答案1

得分: 7

你可以使用flag.Set("flagname", "whatever")来设置标志的值。

或者,如果你想对选项进行其他操作(检查默认值,查看是否已更改等),你可以使用f := flag.Lookup("flagname"),然后使用f.Value.Set("whatever")(以及其他方法)。

无论哪种情况,如果你需要在flag.CommandLine集合之外的其他地方使用,都有相应的flag.FlagSet方法。

Playground示例

英文:

You can just do flag.Set("flagname", "whatever").

Or if you want to do something else to the option (check the default, see if it's already been changed, etc) you can use f := flag.Lookup("flagname") and then f.Value.Set("whatever") (as well as other methods).

In either case there are matching flag.FlagSet methods if you need this on something other than the flag.CommandLine set.

<kbd>Playground example</kbd>

huangapple
  • 本文由 发表于 2015年3月22日 03:00:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/29186781.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定