Home >Backend Development >Golang >How Can I Successfully Retrieve Return Values from a Python Function Called by a Go Program?
One common task when working with multiple languages in a project is the ability to invoke functions from one language within another. In this case, we're exploring how to call a Python function from a Go program and retrieve its return value.
In an initial attempt, the following Go code was used:
package main import ( "fmt" "os/exec" ) func main() { cmd := exec.Command("python", "-c", fmt.Sprintf("'import pythonfile; print pythonfile.cat_strings(\"%s\", \"%s\")'", "foo", "bar")) out, err := cmd.CombinedOutput() if err != nil { fmt.Println(err) return } fmt.Println(string(out)) }
However, this approach encountered an issue where the return value from the Python function was not being captured in the Go program. The output showed an empty string, " ".
The problem arose due to the way the Python command was formatted. The quotes surrounding the command itself were leading to the Python interpreter treating the command as a single string instead of a list of arguments.
To resolve the issue, the quotes surrounding the command were removed. The following Go code demonstrates the solution:
package main import ( "fmt" "os/exec" ) func main() { cmd := exec.Command("python", "-c", "import pythonfile; print pythonfile.cat_strings('foo', 'bar')") out, err := cmd.CombinedOutput() if err != nil { fmt.Println(err) return } fmt.Println(string(out)) }
By removing the quotes, the command is now executed as intended, and the return value from the Python function can be properly captured in the Go program.
The above is the detailed content of How Can I Successfully Retrieve Return Values from a Python Function Called by a Go Program?. For more information, please follow other related articles on the PHP Chinese website!