Home >Backend Development >Golang >How to Properly Pass Python Function Return Values to Go?

How to Properly Pass Python Function Return Values to Go?

Barbara Streisand
Barbara StreisandOriginal
2024-12-01 02:40:101052browse

How to Properly Pass Python Function Return Values to Go?

Passing Python Function Return Values to Go

This article addresses the issue of invoking a Python function from within a Go program and accessing its return value. The scenario encountered involves calling a Python function defined in an external file and retrieving its return data for further processing in Go.

In the example provided, a Go program attempts to execute a Python command using exec.Command, but fails to receive any return data. An initial theory is that the return value is printed instead of being returned by the Python function. However, this is dismissed as it would violate the assumption that the function is part of a larger Python utility module.

Upon further investigation, it is found that the issue lies in the construction of the Python command. By removing the enclosing quote around the command itself, the following working code is obtained:

Go Code:

package main

import (
    "fmt"
    "os/exec"
)

func main() {
    cmd := exec.Command("python", "-c", "import pythonfile; print pythonfile.cat_strings('foo', 'bar')")
    fmt.Println(cmd.Args)
    out, err := cmd.CombinedOutput()
    if err != nil { fmt.Println(err); }
    fmt.Println(string(out))
}

The key modification is the removal of the quote around the Python command. This allows the correct command to be executed and the return value to be captured.

The above is the detailed content of How to Properly Pass Python Function Return Values to Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn