Calling Python function from Go and getting the function return value

前端 未结 1 432
無奈伤痛
無奈伤痛 2020-12-23 15:25

I am writing a Go 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

相关标签:
1条回答
  • 2020-12-23 16:04

    I managed to have some working code for this by simply removing the quote around the command itself:

    package main
    
    import "fmt"
    import "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))
    }
    

    And sure enough, in the source, you have this function (for Windows, at least, I don't know if that works for other OSes):

    // EscapeArg rewrites command line argument s as prescribed
    // in http://msdn.microsoft.com/en-us/library/ms880421.
    // This function returns "" (2 double quotes) if s is empty.
    // Alternatively, these transformations are done:
    // - every back slash (\) is doubled, but only if immediately
    //   followed by double quote (");
    // - every double quote (") is escaped by back slash (\);
    // - finally, s is wrapped with double quotes (arg -> "arg"),
    //   but only if there is space or tab inside s.
    func EscapeArg(s string) string { ...
    

    So your code is ending up passing the following command line call:

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

    Which, if tested, evaluates to a string and returns nothing, hence the 0-length output.

    0 讨论(0)
提交回复
热议问题