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?
Asked
Active
Viewed 120 times
1 Answers
2
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

biw
- 3,000
- 4
- 23
- 40
-
1There'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. – Linear Oct 23 '14 at 04:51
-
@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. – biw Oct 23 '14 at 06:13