What is the best way to get the path to the executable at runtime?

If my go program can be executed in different ways (cron, monit, etc.), what is the most reliable way to get the directory containing the executable at runtime?

In python, this will be a variable:

os.path.realpath(__file__)
+5
source share
3 answers

This is probably the same as in C, in other words, there is no portable error checking method. See How to find the location of an executable in C?

+3
source

One quick fix in go (not necessarily universal) is suggested by Andrew Brookins in the Go To section : How to get the directory of the current file ":

runtime.Caller().
goroutines, .

.
:

_, filename, _, _ := runtime.Caller(1)
f, err := os.Open(path.Join(path.Dir(filename), "data.csv"))
+2

The best way I've found is to use os.Getwd(). See the documentation here: golang doc

-2
source

All Articles