Closed2

GoからPythonを実行する

nasanasa

golangでpythonを動かす

Goでpythonを動かすコードを見て色々気になったので調べてしまった。
これで動かせるらしい。python3.9のpathが違うので動かなかったけど。

// #cgo pkg-config: python3
// #include <Python.h>
import "C"

func main() {
	//  最後にPythonインタプリタ終了
	defer C.Py_Finalize()
	// Pythonインタプリタの初期化
	C.Py_Initialize()
	// GoのstringをCのcharに型変換(変換しないとPyRun_SimpleStringに型合ってないよって怒られる)
	// cannot use "print(\"Hello, World!\")" (type string) as type *_Ctype_char in argument to _Cfunc_PyRun_SimpleString
	pyCodeStr := `print("Hello, World!")`
	pyCodeChar := C.CString(pyCodeStr)
	// Pythonコードを文字列として受け取ってインタプリタ上で実行
	C.PyRun_SimpleString(pyCodeChar)
}

L1でpythonのヘッダーファイルをincludeする。(ヘッダーには定義だけが入ってるらしい)
L2でオブジェクトファイルをリンクする。(僕の手物にはdylibがあったのでダイナミックライブラリが使われてる?)
あとはCからpythonをインタプリタを呼べばいい感じになるらしい。

evalを読んで頑張るのではなくPyRun_SimpleStringなどのCからぴゅっと呼べるインタフェースが提供されているのが良いなと思った。

serverで動かし続ける想定なのでGCが動くかなど気にする必要がありそう。

nasanasa

symbolがない

arm64のsymbolが無いと起こられる。

:) % go run test.go
# command-line-arguments
Undefined symbols for architecture arm64:
  "_PyRun_SimpleStringFlags", referenced from:
      __cgo_aeed0b93982c_Cfunc_PyRun_SimpleString in _x002.o
  "_Py_Finalize", referenced from:
      __cgo_aeed0b93982c_Cfunc_Py_Finalize in _x002.o
     (maybe you meant: __cgo_aeed0b93982c_Cfunc_Py_Finalize)
  "_Py_Initialize", referenced from:
      __cgo_aeed0b93982c_Cfunc_Py_Initialize in _x002.o
     (maybe you meant: __cgo_aeed0b93982c_Cfunc_Py_Initialize)
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

pkg-configがうまく動いてないのかなーと思い直接オプションを書くようにした。

:( % pkg-config --cflags python-3.9-embed
-I/opt/homebrew/Cellar/python@3.9/3.9.12/Frameworks/Python.framework/Versions/3.9/include/python3.9

:) % pkg-config --libs python-3.9-embed
-L/opt/homebrew/Cellar/python@3.9/3.9.12/Frameworks/Python.framework/Versions/3.9/lib -lpython3.9
- // #cgo pkg-config: python3
+ // #cgo CFLAGS: -I/opt/homebrew/Cellar/python@3.9/3.9.12/Frameworks/Python.framework/Versions/3.9/include/python3.9
+ // #cgo LDFLAGS: -L/opt/homebrew/Cellar/python@3.9/3.9.12/Frameworks/Python.framework/Versions/3.9/lib -lpython3.9

動いた!何だったのだろうか。

:( % go run test.go
Hello, World!
このスクラップは2023/01/28にクローズされました