Process Library for Go

Run commands, stream output, and manage subprocesses in Go.
Quick Start · Examples · Behavior · API
Installation
Requires Go 1.27 or newer. Install Process in your Go module:
go get github.com/goforj/processQuick Start
Save this program as main.go in the same module, then run go run .:
package main
import (
"fmt"
"log"
"github.com/goforj/process"
)
// main prints the installed Go version.
func main() {
result, err := process.Command("go", "version").Run()
if err != nil {
log.Fatal(err)
}
// A command's exit status is separate from an execution error.
if !result.OK() {
log.Fatalf("go exited with status %d: %s", result.ExitCode, result.Stderr)
}
fmt.Print(result.Stdout)
}Reuse settings across commands with a Runner. See execution and logging behavior for timeouts, exit handling, and application tests.
Runnable Examples
The testing example shows dependency injection and recorded commands. Browse the complete programs for JSON decoding, streaming output, background execution, and pipelines.
API Index
| Group | Functions |
|---|---|
| Construction | Command |
| Runner | NewRunner · Runner.Run |
| Testing | processtest.Fake |
| Execution | Run · OutputTrimmed · Start |
| Context | WithContext · WithTimeout |
| OS Controls | WithProcessTree |
| Environment | Env · EnvOnly |
| Input | StdinString |
| Streaming | OnStdout · StdoutWriter |
| Output | DisableBuffering |
| Decoding | DecodeJSON · DecodeYAML · As · Into |
| Pipelining | Pipe · PipelineResults |
| Process | Done · Wait · PID · GracefulShutdown |
| Results | OK · IsExitCode · EnsureSuccessful |
| Shadow Print | ShadowPrint · WithMask |
See the complete API documentation for every exported type and method.
Arguments
Arg
Arg appends arguments to the command.
cmd := process.Command("printf").Arg("hello")
out, err := cmd.Output()
if err != nil {
return err
}
fmt.Print(out)
// Output:
// helloConstruction
Command
Command constructs a new command without executing it.
cmd := process.Command("printf", "hello")
out, err := cmd.Output()
if err != nil {
return err
}
fmt.Print(out)
// Output:
// helloContext
WithContext
WithContext binds the command to a context. A nil context is normalized to context.Background when execution begins.
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
res, err := process.Command("go", "env", "GOOS").WithContext(ctx).Run()
if err != nil {
return err
}
fmt.Println(res.ExitCode == 0)
// Output:
// trueWithDeadline
WithDeadline binds the command to a deadline. Replacing a deadline retains the context previously supplied through WithContext as its parent.
res, err := process.Command("go", "env", "GOOS").WithDeadline(time.Now().Add(2 * time.Second)).Run()
if err != nil {
return err
}
fmt.Println(res.ExitCode == 0)
// Output:
// trueWithTimeout
WithTimeout binds the command to a timeout. Replacing a timeout retains the context previously supplied through WithContext as its parent.
res, err := process.Command("go", "env", "GOOS").WithTimeout(2 * time.Second).Run()
if err != nil {
return err
}
fmt.Println(res.ExitCode == 0)
// Output:
// trueDebugging
Args
Args returns the argv slice used for execution.
cmd := process.Command("go", "env", "GOOS")
fmt.Println(strings.Join(cmd.Args(), " "))
// Output:
// go env GOOSShellEscaped
ShellEscaped returns a shell-escaped string for logging only.
cmd := process.Command("echo", "hello world", "it's")
fmt.Println(cmd.ShellEscaped())
// Output:
// echo 'hello world' "it's"String
String returns a human-readable representation of the command.
cmd := process.Command("echo", "hello world", "it's")
fmt.Println(cmd.String())
// Output:
// echo "hello world" it'sDecoding
As
As executes the command and decodes its selected output into T.
type Product struct {
Name string `json:"name"`
}
product, err := process.Command("printf", `{"name":"Coffee"}`).DecodeJSON().As[Product]()
if err != nil {
return err
}
fmt.Println(product.Name)
// Output:
// CoffeeDecode
Decode configures a custom decoder for this command. Decoding reads from stdout by default; use FromStdout, FromStderr, or FromCombined to select a source.
type payload struct {
Name string
}
decoder := process.DecoderFunc(func(data []byte, dst any) error {
out, ok := dst.(*payload)
if !ok {
return fmt.Errorf("expected *payload")
}
_, val, ok := strings.Cut(string(data), "=")
if !ok {
return fmt.Errorf("invalid payload")
}
out.Name = val
return nil
})
var out payload
if err := process.Command("printf", "name=gopher").
Decode(decoder).
Into(&out); err != nil {
return err
}
fmt.Println(out.Name)
// Output:
// gopherDecodeJSON
DecodeJSON configures JSON decoding for this command. Decoding reads from stdout by default; use FromStdout, FromStderr, or FromCombined to select a source.
type payload struct {
Name string `json:"name"`
}
var out payload
if err := process.Command("printf", `{"name":"gopher"}`).
DecodeJSON().
Into(&out); err != nil {
return err
}
fmt.Println(out.Name)
// Output:
// gopherDecodeWith
DecodeWith executes the command and decodes stdout into dst.
type payload struct {
Name string `json:"name"`
}
var out payload
if err := process.Command("printf", `{"name":"gopher"}`).
DecodeWith(&out, process.DecoderFunc(json.Unmarshal)); err != nil {
return err
}
fmt.Println(out.Name)
// Output:
// gopherDecodeYAML
DecodeYAML configures YAML decoding for this command. Decoding reads from stdout by default; use FromStdout, FromStderr, or FromCombined to select a source.
type payload struct {
Name string `yaml:"name"`
}
var out payload
if err := process.Command("printf", "name: gopher").
DecodeYAML().
Into(&out); err != nil {
return err
}
fmt.Println(out.Name)
// Output:
// gopherDecoderFunc.Decode
Decode implements Decoder.
decoder := process.DecoderFunc(json.Unmarshal)
var product struct {
Name string `json:"name"`
}
if err := decoder.Decode([]byte(`{"name":"Coffee"}`), &product); err != nil {
return err
}
fmt.Println(product.Name)
// Output:
// CoffeeFromCombined
FromCombined decodes from combined stdout+stderr.
type payload struct {
Name string `json:"name"`
}
var out payload
if err := process.Command("sh", "-c", `printf '{"name":"gopher"}'`).
DecodeJSON().
FromCombined().
Into(&out); err != nil {
return err
}
fmt.Println(out.Name)
// Output:
// gopherFromStderr
FromStderr decodes from stderr.
type payload struct {
Name string `json:"name"`
}
var out payload
if err := process.Command("sh", "-c", `printf '{"name":"gopher"}' 1>&2`).
DecodeJSON().
FromStderr().
Into(&out); err != nil {
return err
}
fmt.Println(out.Name)
// Output:
// gopherFromStdout
FromStdout decodes from stdout (default).
type payload struct {
Name string `json:"name"`
}
var out payload
if err := process.Command("printf", `{"name":"gopher"}`).
DecodeJSON().
FromStdout().
Into(&out); err != nil {
return err
}
fmt.Println(out.Name)
// Output:
// gopherInto
Into executes the command and decodes into dst.
type payload struct {
Name string `json:"name"`
}
var out payload
if err := process.Command("printf", `{"name":"gopher"}`).
DecodeJSON().
Into(&out); err != nil {
return err
}
fmt.Println(out.Name)
// Output:
// gopherTrim
Trim trims whitespace before decoding.
type payload struct {
Name string `json:"name"`
}
var out payload
if err := process.Command("printf", " {\"name\":\"gopher\"} ").
DecodeJSON().
Trim().
Into(&out); err != nil {
return err
}
fmt.Println(out.Name)
// Output:
// gopherEnvironment
Env
Env adds environment variables to the command.
cmd := process.Command("go", "env", "GOOS").Env("MODE=prod")
fmt.Println(strings.Contains(strings.Join(cmd.EnvList(), ","), "MODE=prod"))
// Output:
// trueEnvAppend
EnvAppend merges variables into the inherited environment.
cmd := process.Command("go", "env", "GOOS").EnvAppend(map[string]string{"A": "1"})
fmt.Println(strings.Contains(strings.Join(cmd.EnvList(), ","), "A=1"))
// Output:
// trueEnvInherit
EnvInherit restores default environment inheritance.
cmd := process.Command("go", "env", "GOOS").EnvInherit()
fmt.Println(len(cmd.EnvList()) > 0)
// Output:
// trueEnvList
EnvList returns the environment list for execution.
cmd := process.Command("go", "env", "GOOS").EnvOnly(map[string]string{"A": "1"})
fmt.Println(strings.Join(cmd.EnvList(), ","))
// Output:
// A=1EnvOnly
EnvOnly ignores the parent environment.
cmd := process.Command("go", "env", "GOOS").EnvOnly(map[string]string{"A": "1"})
fmt.Println(strings.Join(cmd.EnvList(), ","))
// Output:
// A=1Errors
Error
Error returns the wrapped error message when available.
err := process.ErrExec{Err: fmt.Errorf("boom")}
fmt.Println(err.Error())
// Output:
// boomExitError.Error
Error reports the exit status without including potentially sensitive output.
err := process.ExitError{Result: process.Result{ExitCode: 7}}
fmt.Println(err.Error())
// Output:
// process: command exited with status 7TimeoutError.Error
Error distinguishes inactivity from an elapsed total deadline.
err := process.TimeoutError{Idle: true}
fmt.Println(err.Error())
// Output:
// process: idle timeout exceededTimeoutError.Unwrap
Unwrap makes timeouts recognizable through errors.Is with context.DeadlineExceeded.
err := process.TimeoutError{}
fmt.Println(errors.Is(err.Unwrap(), context.DeadlineExceeded))
// Output:
// trueUnwrap
Unwrap exposes the underlying error.
err := process.ErrExec{Err: fmt.Errorf("boom")}
fmt.Println(err.Unwrap() != nil)
// Output:
// trueExecution
CombinedOutput
CombinedOutput executes the command and returns stdout and stderr in observed chunk order plus any execution error. Exact byte interleaving between the two operating-system streams is inherently scheduler-dependent.
output, err := process.Command("sh", "-c", "printf warning >&2").CombinedOutput()
if err != nil {
return err
}
fmt.Println(output)
// Output:
// warningOnExecCmd
OnExecCmd registers a callback to mutate the underlying exec.Cmd before process attaches its stdin, output capture, and pipeline wiring. Use it for fields such as SysProcAttr; process owns Stdin, Stdout, and Stderr during execution.
result, err := process.Command("go", "version").OnExecCmd(func(cmd *exec.Cmd) {
cmd.WaitDelay = time.Second
}).Run()
if err != nil {
return err
}
fmt.Println(result.OK())
// Output:
// trueOutput
Output executes the command and returns stdout and any error.
out, err := process.Command("printf", "hello").Output()
if err != nil {
return err
}
fmt.Print(out)
// Output:
// helloOutputBytes
OutputBytes executes the command and returns stdout bytes and any error.
out, err := process.Command("printf", "hello").OutputBytes()
if err != nil {
return err
}
fmt.Println(string(out))
// Output:
// helloOutputTrimmed
OutputTrimmed executes the command and returns trimmed stdout and any error.
out, err := process.Command("printf", "hello\n").OutputTrimmed()
if err != nil {
return err
}
fmt.Println(out)
// Output:
// helloRun
Run executes the command and returns the result and any execution error. A non-zero exit code is represented in Result and does not itself produce an error.
res, err := process.Command("go", "env", "GOOS").Run()
if err != nil {
return err
}
fmt.Println(res.ExitCode == 0)
// Output:
// trueStart
Start executes the command asynchronously. Startup still completes synchronously, so a returned Process represents either a fully started pipeline or a completed error.
proc := process.Command("go", "env", "GOOS").Start()
res, err := proc.Wait()
if err != nil {
return err
}
fmt.Println(res.ExitCode == 0)
// Output:
// trueInput
StdinBytes
StdinBytes sets stdin from a copy of bytes so later caller mutation cannot change the command input.
out, err := process.Command("cat").
StdinBytes([]byte("hi")).
Output()
if err != nil {
return err
}
fmt.Println(out)
// Output:
// hiStdinFile
StdinFile sets stdin from a file.
file, err := os.CreateTemp("", "process-input-*")
if err != nil {
return err
}
defer os.Remove(file.Name())
defer file.Close()
if _, err := file.WriteString("hello"); err != nil {
return err
}
if _, err := file.Seek(0, 0); err != nil {
return err
}
output, err := process.Command("cat").StdinFile(file).Output()
if err != nil {
return err
}
fmt.Println(output)
// Output:
// helloStdinReader
StdinReader sets stdin from an io.Reader.
out, err := process.Command("cat").
StdinReader(strings.NewReader("hi")).
Output()
if err != nil {
return err
}
fmt.Println(out)
// Output:
// hiStdinString
StdinString sets stdin from a string.
out, err := process.Command("cat").
StdinString("hi").
Output()
if err != nil {
return err
}
fmt.Println(out)
// Output:
// hiOS Controls
CreationFlags
CreationFlags is a no-op on non-Windows platforms; on Windows it sets process creation flags.
result, err := process.Command("go", "version").CreationFlags(process.CreateNewProcessGroup).Run()
if err != nil {
return err
}
fmt.Println(result.OK())
// Output:
// trueHideWindow
HideWindow is a no-op on non-Windows platforms; on Windows it hides console windows.
result, err := process.Command("go", "version").HideWindow(true).Run()
if err != nil {
return err
}
fmt.Println(result.OK())
// Output:
// truePdeathsig
Pdeathsig signals the child when its creating OS thread exits on Linux. It is a no-op on other platforms.
out, err := process.Command("printf", "ok").Pdeathsig(syscall.SIGTERM).Output()
if err != nil {
return err
}
fmt.Print(out)
// Output:
// okSetpgid
Setpgid places the child in a new process group for group signals.
out, err := process.Command("printf", "ok").Setpgid(true).Output()
if err != nil {
return err
}
fmt.Print(out)
// Output:
// okSetsid
Setsid starts the child in a new session, detaching it from the terminal.
out, err := process.Command("printf", "ok").Setsid(true).Output()
if err != nil {
return err
}
fmt.Print(out)
// Output:
// okWithProcessTree
WithProcessTree includes descendants when canceling or terminating a command. It owns a process group on Linux and macOS and a job object on Windows. Surviving members are terminated when the direct child exits. Unix children that create another group or session leave this scope. Unsupported platforms return an error before starting the command. The option applies to every stage in a pipeline and preserves the default behavior of other commands.
result, err := process.Command("go", "version").WithProcessTree().Run()
if err != nil {
return err
}
fmt.Println(result.OK())
// Output:
// trueOutput
DisableBuffering
DisableBuffering stops retaining this stage's stdout and stderr in results. Custom writers, callbacks, and pipeline connections still receive output. CombinedOutput also returns no captured bytes for this stage. Line callbacks retain an unfinished line until its newline or the end of the stream.
var output strings.Builder
result, err := process.Command("go", "env", "GOOS").
StdoutWriter(&output).
DisableBuffering().
Run()
if err != nil {
return err
}
fmt.Println("streamed:", output.Len() > 0, "captured bytes:", len(result.Stdout))
// Output:
// streamed: true captured bytes: 0Pipelining
Pipe
Pipe appends a new command to the pipeline. Pipelines run on all platforms. Configuration called on the returned Cmd applies to the new stage; configure the current stage before Pipe when it needs different environment, context, or I/O.
out, err := process.Command("printf", "go").
Pipe("tr", "a-z", "A-Z").
OutputTrimmed()
if err != nil {
return err
}
fmt.Println(out)
// Output:
// GOPipeBestEffort
PipeBestEffort selects the last stage as the primary result while surfacing the first execution error. Every stage is started concurrently.
res, err := process.Command("false").
Pipe("printf", "ok").
PipeBestEffort().
Run()
if err != nil {
return err
}
fmt.Print(res.Stdout)
// Output:
// okPipeStrict
PipeStrict selects the first stage with an execution error or non-zero exit as the primary result. Every stage is still started concurrently.
res, err := process.Command("false").
Pipe("printf", "ok").
PipeStrict().
Run()
if err != nil {
return err
}
fmt.Println(res.ExitCode != 0)
// Output:
// truePipelineResults
PipelineResults executes the command and returns per-stage results and the first execution error. Non-zero exit codes remain data in their corresponding Result.
results, err := process.Command("printf", "go").Pipe("tr", "a-z", "A-Z").PipelineResults()
if err != nil {
return err
}
fmt.Println(results[0].Stdout, results[1].Stdout)
// Output:
// go GOProcess
Done
Done returns a channel that closes after all pipeline stages exit and their output is collected. Wait can then retrieve the immutable result without blocking.
proc := process.Command("go", "env", "GOOS").Start()
<-proc.Done()
result, err := proc.Wait()
if err != nil {
return err
}
fmt.Println(result.OK())
// Output:
// trueGracefulShutdown
GracefulShutdown sends a signal and escalates to kill after the timeout.
proc := process.Command("sleep", "10").Start()
if err := proc.GracefulShutdown(os.Interrupt, time.Second); err != nil {
return err
}
result, err := proc.Wait()
if err != nil {
return err
}
fmt.Println(result.ExitCode != 0)
// Output:
// trueInterrupt
Interrupt sends an interrupt signal to the process.
proc := process.Command("sleep", "10").Start()
if err := proc.Interrupt(); err != nil {
return err
}
result, err := proc.Wait()
if err != nil {
return err
}
fmt.Println(result.ExitCode != 0)
// Output:
// trueKillAfter
KillAfter terminates the process after the given duration.
proc := process.Command("sleep", "10").Start()
proc.KillAfter(100 * time.Millisecond)
result, err := proc.Wait()
if err != nil {
return err
}
fmt.Println(result.ExitCode != 0)
// Output:
// truePID
PID returns the first pipeline stage's assigned process ID, or zero if no stage started. The ID remains available after completion and can be reused by the OS.
proc := process.Command("go", "env", "GOOS").Start()
if _, err := proc.Wait(); err != nil {
return err
}
fmt.Println(proc.PID() > 0)
// Output:
// truePIDs
PIDs returns an independent slice of assigned process IDs in pipeline order. IDs describe started stages, including stages that have already exited.
proc := process.Command("go", "env", "GOOS").Start()
if _, err := proc.Wait(); err != nil {
return err
}
fmt.Println(len(proc.PIDs()))
// Output:
// 1Running
Running reports whether a started pipeline is still collecting its result. It returns false for an unstarted handle and after Done closes.
proc := process.Command("go", "env", "GOOS").Start()
if _, err := proc.Wait(); err != nil {
return err
}
fmt.Println(proc.Running())
// Output:
// falseSend
Send sends a signal to the process.
proc := process.Command("sleep", "10").Start()
if err := proc.Send(os.Interrupt); err != nil {
return err
}
result, err := proc.Wait()
if err != nil {
return err
}
fmt.Println(result.ExitCode != 0)
// Output:
// trueTerminate
Terminate kills the process immediately.
proc := process.Command("sleep", "10").Start()
if err := proc.Terminate(); err != nil {
return err
}
result, err := proc.Wait()
if err != nil {
return err
}
fmt.Println(result.ExitCode != 0)
// Output:
// trueWait
Wait waits for the command to complete and returns the result and any error.
proc := process.Command("go", "version").Start()
result, err := proc.Wait()
if err != nil {
return err
}
fmt.Println(result.OK())
// Output:
// trueResults
EnsureSuccessful
EnsureSuccessful returns the execution error or an ExitError for a nonzero status. It returns nil for success and does not change the Result.
result, err := process.Command("go", "version").Run()
if err != nil {
return err
}
fmt.Println(result.EnsureSuccessful() == nil)
// Output:
// trueIsExitCode
IsExitCode reports whether the exit code matches.
res, err := process.Command("go", "env", "GOOS").Run()
if err != nil {
return err
}
fmt.Println(res.IsExitCode(0))
// Output:
// trueIsSignal
IsSignal reports whether the command terminated due to a signal.
res, err := process.Command("go", "env", "GOOS").Run()
if err != nil {
return err
}
fmt.Println(res.IsSignal(os.Interrupt))
// Output:
// falseOK
OK reports whether the command exited cleanly without errors.
res, err := process.Command("go", "env", "GOOS").Run()
if err != nil {
return err
}
fmt.Println(res.OK())
// Output:
// trueRunner
NewRunner
NewRunner returns reusable settings without starting a process.
runner := process.NewRunner().Timeout(5 * time.Second).CheckExit()
result, err := runner.Run(context.Background(), "go", "version")
if err != nil {
return err
}
fmt.Println(result.OK())
// Output:
// trueRunner.CheckExit
CheckExit returns a Runner that reports a nonzero child exit as an ExitError. The default keeps nonzero exits in Result.ExitCode without returning an error.
_, err := process.NewRunner().CheckExit().Run(context.Background(), "sh", "-c", "exit 7")
var exit *process.ExitError
if !errors.As(err, &exit) {
return err
}
fmt.Println(exit.Result.ExitCode)
// Output:
// 7Runner.Dir
Dir returns a Runner using path as each child's working directory.
result, err := process.NewRunner().Dir(os.TempDir()).Run(context.Background(), "go", "version")
if err != nil {
return err
}
fmt.Println(result.OK())
// Output:
// trueRunner.DisableBuffering
DisableBuffering returns a Runner that streams output without retaining it.
var output strings.Builder
result, err := process.NewRunner().Stdout(&output).DisableBuffering().
Run(context.Background(), "printf", "ready")
if err != nil {
return err
}
fmt.Println(output.String(), len(result.Stdout))
// Output:
// ready 0Runner.Env
Env returns a Runner with one environment override. An empty value sets an empty variable; use UnsetEnv to remove a variable from the child environment.
result, err := process.NewRunner().Env("MODE", "production").Run(context.Background(), "env")
if err != nil {
return err
}
fmt.Println(strings.Contains(result.Stdout, "MODE=production"))
// Output:
// trueRunner.IdleTimeout
IdleTimeout returns a Runner that cancels after d without stdout or stderr activity. Any nonempty output chunk resets the limit, even without a newline. A nonpositive duration disables this limit.
_, err := process.NewRunner().IdleTimeout(time.Second).Run(context.Background(), "sleep", "10")
var timeout *process.TimeoutError
fmt.Println(errors.As(err, &timeout) && timeout.Idle)
// Output:
// trueRunner.Input
Input returns a Runner that supplies a fresh reader of input to each child.
result, err := process.NewRunner().Input("request").Run(context.Background(), "cat")
if err != nil {
return err
}
fmt.Println(result.Stdout)
// Output:
// requestRunner.Run
Run executes a fresh command using these settings. Arguments are passed directly to the executable. A nil context is treated as context.Background.
runner := process.NewRunner().Env("GOTOOLCHAIN", "local")
result, err := runner.Run(context.Background(), "go", "version")
if err != nil {
return err
}
fmt.Println(result.OK())
// Output:
// trueRunner.Start
Start starts a fresh command and reports startup failures immediately. The returned handle supports the existing Process lifecycle methods. Its Wait result follows this Runner's timeout and CheckExit policies.
child, err := process.NewRunner().Start(context.Background(), "go", "version")
if err != nil {
return err
}
result, err := child.Wait()
if err != nil {
return err
}
fmt.Println(result.OK())
// Output:
// trueRunner.Stderr
Stderr returns a Runner that streams stderr to w as well as capturing it. The caller owns w. A nil writer disables streaming.
var output strings.Builder
result, err := process.NewRunner().Stderr(&output).Run(context.Background(), "sh", "-c", "printf warning >&2")
if err != nil {
return err
}
fmt.Println(output.String(), result.Stderr)
// Output:
// warning warningRunner.Stdout
Stdout returns a Runner that streams stdout to w as well as capturing it. The caller owns w. A nil writer disables streaming.
var output strings.Builder
result, err := process.NewRunner().Stdout(&output).Run(context.Background(), "printf", "ready")
if err != nil {
return err
}
fmt.Println(output.String(), result.Stdout)
// Output:
// ready readyRunner.Timeout
Timeout returns a Runner with a total limit starting at each Run or Start call. A nonpositive duration disables this limit. The caller's context still applies.
result, err := process.NewRunner().Timeout(5*time.Second).Run(context.Background(), "go", "version")
if err != nil {
return err
}
fmt.Println(result.OK())
// Output:
// trueRunner.UnsetEnv
UnsetEnv returns a Runner that removes key from each child's environment.
result, err := process.NewRunner().Env("EXAMPLE_TOKEN", "test").UnsetEnv("EXAMPLE_TOKEN").
Run(context.Background(), "env")
if err != nil {
return err
}
fmt.Println(strings.Contains(result.Stdout, "EXAMPLE_TOKEN="))
// Output:
// falseRunner.WaitDelay
WaitDelay returns a Runner that bounds output-pipe draining after the child exits or its context is canceled. A nonpositive duration leaves draining unlimited. This does not interrupt a caller-owned writer blocked in Write.
result, err := process.NewRunner().Timeout(5*time.Second).WaitDelay(time.Second).
Run(context.Background(), "go", "version")
if err != nil {
return err
}
fmt.Println(result.OK())
// Output:
// trueRunner.WithProcessTree
WithProcessTree returns a Runner that includes descendants in cancellation and termination. The native ownership and platform limits match Cmd.WithProcessTree.
runner := process.NewRunner().WithProcessTree().Timeout(5 * time.Second)
result, err := runner.Run(context.Background(), "go", "version")
if err != nil {
return err
}
fmt.Println(result.OK())
// Output:
// trueRunner.WithoutInheritingEnv
WithoutInheritingEnv returns a Runner that starts with an empty environment. Explicit Env settings are retained. Executable lookup still uses the parent's PATH, as with os/exec; use an absolute program path to control lookup.
result, err := process.NewRunner().WithoutInheritingEnv().Env("MODE", "test").
Run(context.Background(), "env")
if err != nil {
return err
}
fmt.Println(strings.TrimSpace(result.Stdout))
// Output:
// MODE=testShadow Print
ShadowOff
ShadowOff disables shadow printing for this command chain, preserving configuration.
result, err := process.Command("printf", "hello").ShadowPrint().ShadowOff().Run()
if err != nil {
return err
}
fmt.Println(result.Stdout)
// Output:
// helloShadowOn
ShadowOn enables shadow printing using the previously configured options.
cmd := process.Command("printf", "hello").ShadowPrint(process.WithPrefix("build"))
cmd.ShadowOff()
result, err := cmd.ShadowOn().Run()
if err != nil {
return err
}
fmt.Println(result.Stdout)
// Output:
// helloShadowPrint
ShadowPrint configures shadow printing for this command chain.
result, err := process.Command("printf", "hello").ShadowPrint().Run()
if err != nil {
return err
}
fmt.Println(result.Stdout)
// Output:
// helloWithFormatter
WithFormatter sets a formatter for ShadowPrint output.
formatter := func(event process.ShadowEvent) string {
return fmt.Sprintf("%s: %s", event.Phase, event.Command)
}
result, err := process.Command("printf", "hello").ShadowPrint(process.WithFormatter(formatter)).Run()
if err != nil {
return err
}
fmt.Println(result.Stdout)
// Output:
// helloWithMask
WithMask applies a masker to the shadow-printed command string.
mask := func(command string) string { return strings.ReplaceAll(command, "secret", "***") }
result, err := process.Command("printf", "secret").ShadowPrint(process.WithMask(mask)).Run()
if err != nil {
return err
}
fmt.Println(result.OK())
// Output:
// trueWithPrefix
WithPrefix sets the shadow print prefix.
result, err := process.Command("printf", "hello").ShadowPrint(process.WithPrefix("build")).Run()
if err != nil {
return err
}
fmt.Println(result.Stdout)
// Output:
// helloStreaming
OnStderr
OnStderr registers a line callback for stderr. The final unterminated line is delivered after the process exits. Output callbacks and writers are serialized across one pipeline.
if _, err := process.Command("sh", "-c", "printf 'warning\\n' >&2").
OnStderr(func(line string) { fmt.Println(line) }).Run(); err != nil {
return err
}
// Output:
// warningOnStdout
OnStdout registers a line callback for stdout. The final unterminated line is delivered after the process exits. Output callbacks and writers are serialized across one pipeline.
if _, err := process.Command("printf", "hi\n").
OnStdout(func(line string) { fmt.Println(line) }).
Run(); err != nil {
return err
}
// Output:
// hiStderrWriter
StderrWriter sets a raw writer for stderr.
When the writer is a terminal and no line callbacks or combined output are enabled, process passes stderr through directly and does not buffer it for results. Writer failures are returned as ErrExec after already received bytes are captured.
var output strings.Builder
if _, err := process.Command("sh", "-c", "printf warning >&2").StderrWriter(&output).Run(); err != nil {
return err
}
fmt.Println(output.String())
// Output:
// warningStdoutWriter
StdoutWriter sets a raw writer for stdout.
When the writer is a terminal and no line callbacks or combined output are enabled, process passes stdout through directly and does not buffer it for results. Writer failures are returned as ErrExec after already received bytes are captured.
var out strings.Builder
if _, err := process.Command("printf", "hello").
StdoutWriter(&out).
Run(); err != nil {
return err
}
fmt.Print(out.String())
// Output:
// helloWithPTY
WithPTY attaches stdout/stderr to a pseudo-terminal.
When enabled, stdout and stderr are merged into a single stream. OnStdout and OnStderr both receive the same lines, and Result.Stderr remains empty. Platforms without PTY support return an error when the command runs.
if _, err := process.Command("printf", "hi").
WithPTY().
OnStdout(func(line string) { fmt.Println(line) }).
Run(); err != nil {
return err
}
// Output:
// hiTesting
processtest.Fake
Inject process.Executor into application code. Queue results on a separate fake for each test, then inspect its calls. Unexpected commands return an error and never start a real process.
status := func(ctx context.Context, commands process.Executor) (string, error) {
result, err := commands.Run(ctx, "git", "status", "--short")
if err != nil {
return "", err
}
if err := result.EnsureSuccessful(); err != nil {
return "", err
}
return strings.TrimSpace(result.Stdout), nil
}
var fake processtest.Fake
fake.Queue(process.Result{Stdout: " M README.md\n"})
output, err := status(context.Background(), &fake)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(output)
call := fake.Calls()[0]
fmt.Println(call.Name, strings.Join(call.Args, " "))
_, err = fake.Run(context.Background(), "unexpected-command")
fmt.Println(errors.Is(err, processtest.ErrUnexpectedCommand))
// Output:
// M README.md
// git status --short
// trueWorkingDir
Dir
Dir sets the working directory.
dir, err := filepath.EvalSymlinks(os.TempDir())
if err != nil {
return err
}
out, err := process.Command("pwd").Dir(dir).OutputTrimmed()
if err != nil {
return err
}
fmt.Println(out == dir)
// Output:
// trueDevelopment
make test # Run library, generator, and example tests.
make vet # Check all three Go modules.
make test-examples # Execute examples and check their output.
make test-race # Check library tests for data races.
make generate # Regenerate examples and the API reference from GoDoc.The example suite executes every program and checks its output on Unix. Windows runs the portable Go-command examples and compiles the Unix-specific programs.
Edit the GoDoc examples or the tested fake example before regenerating. The docs and examples modules keep tooling out of the library's module download. Use make help for more commands.
For an existing application, see the migration guide.
Licensed under the MIT License.