Code-Memo

Runtime, args, and environment (os + runtime)

Python’s sys maps to several Go packages: os for argv/env/exit, runtime for interpreter-like introspection.

Program arguments
import "os"

for i, a := range os.Args {
	_, _ = i, a
}
Stdin / stdout / stderr
os.Stdin
os.Stdout
os.Stderr
runtime
import "runtime"

n := runtime.NumCPU()
runtime.GOMAXPROCS(n)

var m runtime.MemStats
runtime.ReadMemStats(&m)

println(runtime.Version()) // Go version
Stack traces
buf := make([]byte, 1<<20)
n := runtime.Stack(buf, true) // all goroutines if true
println(string(buf[:n]))
log.Fatal

Calls os.Exit(1) after printing — defers in main won’t run.

Modules and build info

runtime/debug.ReadBuildInfo() in binaries built as modules exposes module versions.