I have written some code in Python that uses some libraries that are not in Go. I have a web server that I have written in Go and I would like to be able to call a Python program from my Go program and then use the output of the Python program as input in my Go program. Is there anyway to do this?
1 Answer
It's actually relatively easy. All you need to do is use the os/exec library. Here is an example below.
Go Code:
package main
import (
"fmt"
"os/exec"
)
func main() {
cmd := exec.Command("python", "python.py", "foo", "bar")
fmt.Println(cmd.Args)
out, err := cmd.CombinedOutput()
if err != nil { fmt.Println(err); }
fmt.Println(string(out))
}
Python Code:
import sys
for i in range(len(sys.argv)):
print str(i) + ": " + sys.argv[i]
Output From Go Code:
[python python.py foo bar]
0: python.py
1: foo
2: bar
2 Comments
Linear
There's also a couple of Python/Cgo bridges using Cython (so you don't have to relaunch the interpreter every time), but they look abandoned.
biw
@Jsor, ya I was looking at some of them but it seemed like a better idea to run code like this. At least this method is supported unlike the others.