如何用Go的标志包打印用法的位置参数? [英] How to print usage for positional argument with Go's flag package?

查看:90
本文介绍了如何用Go的标志包打印用法的位置参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定这个简单的Go程序,它需要一个命令行参数,我该如何改进它,以便 flag.Usage()给出有用的输出?

 包裹主要

进口(
标记
fmt
os


func main(){
flag.Parse()
if len(flag.Args())== 0 {
flag.Usage()
os.Exit(1)
}

args:= flag.Args()
fmt.Println(args [0])
}

不带参数的当前输出:

$ ./args
./args的用法:
$ b

(即用法为空,因为我找不到使用usage()函数需要哪些参数的方法)。

我可以删除 flag.Usage(),并将其替换为如下所示:

  fmt.Fprintln(os.Stderr,Usage:,os.Args [0],< argument>)

然而,如果 flag.Usage()。特别是它已经处理了可选参数:

  $ ./args -foo 
flag提供但未定义:-foo
./args的用法:


解决方案

flag.Usage()只会为您提供有关已定义标志的有用信息。所以你要么通过 var foo = flag.Int(...)来定义你的参数。



另外选项将是定义您自己的使用处理程序。请参阅下面的一个简单示例,它将打印自定义消息和所有已定义标志的默认值。这样你自定义使用将在 flag.Parse()失败的情况下打印。

 包主
导入(
标记
fmt
os


func myUsage(){
fmt.Printf(Usage:%s [OPTIONS] argument ... \\\
,os.Args [0])
flag.PrintDefaults()
}

func main(){
flag.Usage = myUsage
/ * ... * /
}


Given this simple Go program, which requires exactly one command line argument, how can I improve it so that flag.Usage() gives useful output?

package main

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

func main() {
    flag.Parse()
    if len(flag.Args()) == 0 { 
        flag.Usage()
        os.Exit(1)
    }

    args := flag.Args()
    fmt.Println(args[0])
}

Current output with no arguments given:

$ ./args
Usage of ./args:

(i.e. usage is empty, as I can find no way to tell the usage() function which parameters are required).

I can remove flag.Usage() and replace it with something like this:

fmt.Fprintln(os.Stderr, "Usage:", os.Args[0], "<argument>")

However, I don't want to reinvent the wheel if there's already a good way with flag.Usage(). Especially as it's already handling optional arguments:

$ ./args -foo
flag provided but not defined: -foo
Usage of ./args:

解决方案

flag.Usage() will only give you useful information about the defined flags. So you either define your arguments as flags via var foo = flag.Int(...).

Another option would be to define your own usage handler. see below for a simple example which will print a custom message and the defaults for all defined flags. This way you custom Usage will be printed in case flag.Parse() fails.

package main
import (
    "flag"
    "fmt"
    "os"
)

func myUsage() {
     fmt.Printf("Usage: %s [OPTIONS] argument ...\n", os.Args[0])
     flag.PrintDefaults()
}

func main() {
     flag.Usage = myUsage
     /* ... */
}

这篇关于如何用Go的标志包打印用法的位置参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆