HiveBrain v1.2.0
Get Started
← Back to all entries
patterngoCritical

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
equivalentargvwhat

Problem

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]);
    // ...
}

Solution

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

Code Snippets

import "os"
os.Args[0] // name of the command that it is running as
os.Args[1] // first command line parameter, ...
func usage() {
    fmt.Fprintf(os.Stderr, "usage: %s [inputfile]\n", os.Args[0])
    flag.PrintDefaults()
    os.Exit(2)
}

Context

Stack Overflow Q#3356011, score: 178

Revisions (0)

No revisions yet.