问题描述
从 main.go 中,我必须调用依赖于 Python 运行时的 cpython 文件夹 (mycprog)。文件夹“mycprog”是用 C++ 编写的,但被包装到一个 Python 模块中,这通过 Python 解释器。
程序结构
/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))
}
当我构建 main.go 时,出现此错误
exit status 1
Traceback (most recent call last):
File "<string>",line 1,in <module>
ModuleNotFoundError: No module named 'mycprog'
exec.Command 语法从我的角度来看是错误的,我按照参考中的示例进行操作。
参考:
https://lmjw.github.io/2017/11/26/blog-docker-python-golang.html
如果在导入“C”之后添加导入“mycprog”,我得到
#include
我需要修复 exec.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()