title: Calling Python function from Go and getting the function return value
body: <p>I am writing a <a href="http://golang.org/" rel="noreferrer">Go</a> program.  From this Go program, I would like to call a Python function defined in another file and receive the function's return value so I can use it in subsequent processing in my Go program.  I am having trouble getting any returned data back in my Go program though.  Below is a minimum example of what I thought would work, but apparently doesn't:</p>
  
  <p><strong>gofile.go</strong></p>
  
  <pre><code>package main
  
  import "os/exec"
  import "fmt"
  
  func main() {
       fmt.Println("here we go...")
       program := "python"
       arg0 := "-c"
       arg1 := fmt.Sprintf("'import pythonfile; print pythonfile.cat_strings(\"%s\", \"%s\")'", "foo", "bar")
       cmd := exec.Command(program, arg0, arg1)
       fmt.Println("command args:", cmd.Args)
       out, err := cmd.CombinedOutput()
       if err != nil {
           fmt.Println("Concatenation failed with error:", err.Error())
       return
       }
       fmt.Println("concatentation length: ", len(out))
       fmt.Println("concatenation: ", string(out))
       fmt.Println("...done")
  }
  </code></pre>
  
  <p><strong>pythonfile.py</strong></p>
  
  <pre><code>def cat_strings(a, b):
      return a + b
  </code></pre>
  
  <p>If I call <code>go run gofile</code> I get the following output:</p>
  
  <pre><code>here we go...
  command args: [python -c 'import pythonfile; print pythonfile.cat_strings("foo", "bar")']
  concatentation length:  0
  concatenation:  
  ...done
  </code></pre>
  
  <p>A few notes:</p>
  
  <ul>
  <li>I'm using the <code>-c</code> flag in the Python invocation so I can call the function <code>cat_strings</code> directly.  Assume <code>cat_strings</code> is part of a Python file full of utility functions that are used by other Python programs, hence why I don't have any <code>if __name__ == __main__</code> business.</li>
  <li>I don't want to modify the Python file to <code>print a + b</code> (instead of <code>return a + b</code>); see the prior point about the function being part of a set of utility functions that ought to be callable by other Python code.</li>
  <li>The <code>cat_strings</code> function is fictional and for demonstration purposes; the real function is something I don't want to simply reimplement in Go.  I really am interested in how I can call a Python function from Go and get the return value.</li>
  </ul>