如何在运行时获取自己的程序名称?什么是Go等同于C/C++的argv [0]?对我来说,使用正确的名称生成用法很有用.
更新:添加了一些代码.
package main
import (
"flag"
"fmt"
"os"
)
func usage() {
fmt.Fprintf(os.Stderr, "usage: myprog [inputfile]\n")
flag.PrintDefaults()
os.Exit(2)
}
func main() {
flag.Usage = usage
flag.Parse()
args := flag.Args()
if len(args) < 1 {
fmt.Println("Input file is missing.");
os.Exit(1);
}
fmt.Printf("opening %s\n", args[0]);
// ...
}
Run Code Online (Sandbox Code Playgroud)
cth*_*m06 141
import "os"
os.Args[0] // name of the command that it is running as
os.Args[1] // first command line parameter, ...
Run Code Online (Sandbox Code Playgroud)
参数在http://golang.org/pkg/os/#Variablesos包中公开
如果您要进行参数处理,则首选方法http://golang.org/pkg/flagflag包.专门针对您的情况flag.Usage
您给出的示例的更新:
func usage() {
fmt.Fprintf(os.Stderr, "usage: %s [inputfile]\n", os.Args[0])
flag.PrintDefaults()
os.Exit(2)
}
Run Code Online (Sandbox Code Playgroud)
应该做的伎俩
nos*_*nos 15
使用os.Args[0]从OS包
package main
import "os"
func main() {
println("I am ", os.Args[0])
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
42513 次 |
| 最近记录: |