forked from gotray/go-python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpython.go
101 lines (81 loc) · 2.13 KB
/
python.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package gp
/*
#cgo pkg-config: python3-embed
#include <Python.h>
*/
import "C"
import (
"fmt"
"reflect"
"unsafe"
)
type PyObject = C.PyObject
type PyCFunction = C.PyCFunction
func Initialize() {
C.Py_Initialize()
}
func Finalize() {
C.Py_FinalizeEx()
typeMetaMap = make(map[*C.PyObject]*typeMeta)
pyTypeMap = make(map[reflect.Type]*C.PyObject)
}
// ----------------------------------------------------------------------------
type InputType = C.int
const (
SingleInput InputType = C.Py_single_input
FileInput InputType = C.Py_file_input
EvalInput InputType = C.Py_eval_input
)
func CompileString(code, filename string, start InputType) Object {
ccode := AllocCStr(code)
cfilename := AllocCStr(filename)
o := C.Py_CompileString(ccode, cfilename, C.int(start))
C.free(unsafe.Pointer(ccode))
C.free(unsafe.Pointer(cfilename))
return newObject(o)
}
func EvalCode(code Object, globals, locals Dict) Object {
return newObject(C.PyEval_EvalCode(code.Obj(), globals.Obj(), locals.Obj()))
}
// ----------------------------------------------------------------------------
// llgo:link Cast llgo.staticCast
func Cast[U, T Objecter](obj T) (u U) {
*(*T)(unsafe.Pointer(&u)) = obj
return
}
// ----------------------------------------------------------------------------
func With[T Objecter](obj T, fn func(v T)) T {
obj.object().Call("__enter__")
defer obj.object().Call("__exit__")
fn(obj)
return obj
}
// ----------------------------------------------------------------------------
func MainModule() Module {
return GetModule("__main__")
}
func None() Object {
return newObject(C.Py_None)
}
func Nil() Object {
return Object{}
}
// RunString executes Python code string and returns error if any
func RunString(code string) error {
// Get __main__ module dict for executing code
main := MainModule()
dict := main.Dict()
// Run the code string
codeObj := CompileString(code, "<string>", FileInput)
if codeObj.Nil() {
return fmt.Errorf("failed to compile code")
}
ret := EvalCode(codeObj, dict, dict)
if ret.Nil() {
if err := FetchError(); err != nil {
return err
}
return fmt.Errorf("failed to execute code")
}
return nil
}