Go: Run External Python script

Did you try adding Run() or Output(), as in:

exec.Command("script.py").Run()
exec.Command("job.sh").Run()

You can see it used in "How to execute a simple Windows DOS command in Golang?" (for Windows, but the same idea applies for Unix)

c := exec.Command("job.sh")

if err := c.Run(); err != nil { 
    fmt.Println("Error: ", err)
}   

Or, with Output() as in "Exec a shell command in Go":

cmd := exec.Command("job.sh")
out, err := cmd.Output()

if err != nil {
    println(err.Error())
    return
}

fmt.Println(string(out))

First of all do not forget to make your python script executable (permissions and #!/usr/local/bin/python at the beginning).

After this you can just run something similar to this (notice that it will report you errors and standard output).

package main

import (
    "log"
    "os"
    "os/exec"
)

func main() {
    cmd := exec.Command("script.py")
    cmd.Stdout = os.Stdout
    cmd.Stderr = os.Stderr
    log.Println(cmd.Run())
}

Below worked for me on Windows 10

python := path.Clean(strings.Join([]string{os.Getenv("userprofile"), "Anaconda3", "python.exe"}, "/"))
script := "my_script.py"
cmd := exec.Command("cmd", python, script)
out, err := cmd.Output()
fmt.Println(string(out))
if err != nil {
    log.Fatal(err)
}

Tags:

Exec

Go