From e6ff94c45fb692d7081a5a1710d164d845941b00 Mon Sep 17 00:00:00 2001 From: Shane C Date: Fri, 5 Jul 2024 11:33:12 -0400 Subject: [PATCH] add python command --- cmd/python.go | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 cmd/python.go diff --git a/cmd/python.go b/cmd/python.go new file mode 100644 index 0000000..b1ddc22 --- /dev/null +++ b/cmd/python.go @@ -0,0 +1,38 @@ +package cmd + +import ( + "errors" + "fmt" + "os/exec" + "strings" +) + +var PythonNotFound = errors.New("python not found") + +func Python(args ...string) (output string, err error) { + + if _, err := Which("python3"); err != nil { + if errors.Is(err, ErrNotFound) { + return "", PythonNotFound + } else { + return "", err + } + } + + command := exec.Command("python3", args...) + + outputBytes, err := command.Output() + if err != nil { + var exitErr *exec.ExitError + if errors.As(err, &exitErr) { + if exitErr.ExitCode() == 1 { + return "", ErrNotFound + } else { + return "", fmt.Errorf("command error: %w", err) + } + } + } + + return strings.Trim(string(outputBytes), "\n"), nil + +}