Home >Backend Development >Golang >How Can I Retrieve the Return Value of a Python Function Called from a Go Program?

How Can I Retrieve the Return Value of a Python Function Called from a Go Program?

Barbara Streisand
Barbara StreisandOriginal
2024-11-29 19:28:11775browse

How Can I Retrieve the Return Value of a Python Function Called from a Go Program?

Calling Python Functions from Go with Return Value Retrieval

In this scenario, we aim to bridge the gap between Go and Python by invoking a Python function from a Go program and capturing its return value for further processing. However, initial attempts have proved unsuccessful in retrieving the desired data.

The Stumbling Block

The minimal example provided illustrates the challenge:

package main

import (
    "fmt"
    "os/exec"
)

func main() {
    fmt.Println("here we go...")
    program := "python"
    arg0 := "-c"
    arg1 := fmt.Sprintf("'%s'", "import pythonfile; print pythonfile.cat_strings(\"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("concatenation length:", len(out))
    fmt.Println("concatenation:", string(out))
    fmt.Println("...done")
}

Corresponding Python code:

def cat_strings(a, b):
    return a + b

Executing go run gofile yields:

here we go...
command args: [python -c 'import pythonfile; print pythonfile.cat_strings("foo", "bar")']
concatenation length:  0
concatenation:  
...done

The Solution

Overcoming this obstacle required the judicious removal of unnecessary quotes around the command itself:

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))
}

This modification resulted in a successful retrieval of the function's return value:

$ python -c "import pythonfile; print pythonfile.cat_strings('foo', 'bar')"
foobar

The above is the detailed content of How Can I Retrieve the Return Value of a Python Function Called from a Go Program?. 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