简体   繁体   中英

How to share data between programs written in Go and Python?

From main.go, I have to call a CPython folder (mycprog) which has dependency on Python run time. The folder 'mycprog' is written in C++ but is wrapped into a Python module and this goes thru python interpreter.

Program structure

/src
/main
      main.go 
/mycprog
    a1.cpp (this has a function **object EEEdept::getStaffID()**`)  
    a1.hpp 
    a2.cpp

main.go

package main
    
    // #cgo pkg-config: python3
    
    // #cgo CFLAGS : -I./ -I/usr/include/python3.6m
    
    // #cgo LDFLAGS: -L/usr/lib/python3.6/config-3.6m-x86_64-linux-gnu -L/usr/lib -lpython3.6m -lpthread -ldl -lutil -lm
    
            
    import "C"
    
    import (
    
    "fmt"
    
    "os/exec"
    )
    
    func main() {
    
    cmd := exec.Command("python", "-c", "import mycprog; mycprog.getStaffID()")
       
    out,err := cmd.CombinedOutput()    
    if err != nil {
   
        fmt.Println(err);
    
   }
    
    fmt.Println(string(out))
    }

When I build the main.go, I get this error

exit status 1

Traceback (most recent call last):

File "<string>", line 1, in <module>

ModuleNotFoundError: No module named 'mycprog'

exec.Command syntax is wrong from my end and I followed the example from the reference.

references:

https://lmjw.github.io/2017/11/26/blog-docker-python-golang.html

If import "mycprog" is added after import "C", I get

#include <patchlevel.h> compilation terminated

Which part in the exec.Command I need to fix?

you can try to change working directory after defining command:

cmd := exec.Command("python", "-c", "import mycprog; mycprog.getStaffID()")
cmd.Dir = "your/working/directory"    //directory where is your python code
out,err := cmd.CombinedOutput()  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM