Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's Go's equivalent of argv[0]?

Tags:

go

How can I get my own program's name at runtime? What's Go's equivalent of C/C++'s argv[0]? To me it is useful to generate the usage with the right name.

Update: added some code.

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]);     // ... } 
like image 879
grokus Avatar asked Jul 28 '10 18:07

grokus


People also ask

What is the value of argv 0 ]?

By convention, argv[0] is the command with which the program is invoked. argv[1] is the first command-line argument. The last argument from the command line is argv[argc - 1] , and argv[argc] is always NULL.

How do you use argv 0?

If the value of argc is greater than zero, the string pointed to by argv[0] represents the program name; argv[0][0] shall be the null character if the program name is not available from the host environment. So no, it's only the program name if that name is available.

What is argv [] in C?

The argv argument is a vector of C strings; its elements are the individual command line argument strings. The file name of the program being run is also included in the vector as the first element; the value of argc counts this element.

What is argv 0 and argv 1?

argv[argc] is a NULL pointer. argv[0] holds the name of the program. argv[1] points to the first command line argument and argv[n] points last argument.


2 Answers

import "os" os.Args[0] // name of the command that it is running as os.Args[1] // first command line parameter, ... 

Arguments are exposed in the os package http://golang.org/pkg/os/#Variables

If you're going to do argument handling, the flag package http://golang.org/pkg/flag is the preferred way. Specifically for your case flag.Usage

Update for the example you gave:

func usage() {     fmt.Fprintf(os.Stderr, "usage: %s [inputfile]\n", os.Args[0])     flag.PrintDefaults()     os.Exit(2) } 

should do the trick

like image 182
cthom06 Avatar answered Oct 21 '22 17:10

cthom06


use os.Args[0] from the os package

package main import "os" func main() {     println("I am ", os.Args[0]) } 
like image 30
nos Avatar answered Oct 21 '22 19:10

nos