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
Release: 2024-11-29 19:28:11
Original
686 people have browsed it

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")
}
Copy after login

Corresponding Python code:

def cat_strings(a, b):
    return a + b
Copy after login

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
Copy after login

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))
}
Copy after login

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

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template