Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the current process (executable) name in Go?

Tags:

go

What I am looking for here is the equivalent of C's argv[0].

The flag package only gives access to command line arguments, but not the executable name.

While one can get the process with Getpid(), I haven't found something that will give me access to the whole command line. The syscall command GetCommandLine() seems only to be available on Windows.

like image 872
Pinochle Avatar asked Jan 31 '11 11:01

Pinochle


3 Answers

The traditional argv[0] in C is available in os.Args[0] in Go. The flags package simply processes the slice os.Args[1:]

like image 63
nos Avatar answered Nov 20 '22 02:11

nos


A better way as follows:

filename:=filepath.Base(os.Args[0])

This will present only the application name and remove the path for you.

like image 24
Cyberience Avatar answered Nov 20 '22 02:11

Cyberience


Since Go 1.8, the answer is os.Executable(). Similar to other languages, there is also os.Args[0]. One important distinction is that os.Executable() is guaranteed to return an absolute path.

like image 21
Rodolfo Carvalho Avatar answered Nov 20 '22 01:11

Rodolfo Carvalho