|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "log" |
| 6 | + |
| 7 | + "github.com/sbinet/go-python" |
| 8 | +) |
| 9 | + |
| 10 | +func init() { |
| 11 | + err := python.Initialize() |
| 12 | + if err != nil { |
| 13 | + log.Panic(err.Error()) |
| 14 | + } |
| 15 | +} |
| 16 | + |
| 17 | +func main() { |
| 18 | + module := python.PyImport_ImportModule("values") |
| 19 | + if module == nil { |
| 20 | + log.Fatal("could not import 'values'") |
| 21 | + } |
| 22 | + |
| 23 | + name := module.GetAttrString("__name__") |
| 24 | + if name == nil { |
| 25 | + log.Fatal("could not getattr '__name__'") |
| 26 | + } |
| 27 | + defer name.DecRef() |
| 28 | + fmt.Printf("values.__name__: %q\n", python.PyString_AsString(name)) |
| 29 | + |
| 30 | + sval := module.GetAttrString("sval") |
| 31 | + if sval == nil { |
| 32 | + log.Fatal("could not getattr 'sval'") |
| 33 | + } |
| 34 | + defer sval.DecRef() |
| 35 | + fmt.Printf("values.sval: %q\n", python.PyString_AsString(sval)) |
| 36 | + |
| 37 | + pyival := module.GetAttrString("ival") |
| 38 | + if pyival == nil { |
| 39 | + log.Fatal("could not getattr 'ival'") |
| 40 | + } |
| 41 | + defer pyival.DecRef() |
| 42 | + |
| 43 | + ival := python.PyInt_AsLong(pyival) |
| 44 | + fmt.Printf("values.ival: %d\n", ival) |
| 45 | + |
| 46 | + myfunc := module.GetAttrString("myfunc") |
| 47 | + if myfunc == nil { |
| 48 | + log.Fatal("could not getattr 'myfunc'") |
| 49 | + } |
| 50 | + defer myfunc.DecRef() |
| 51 | + |
| 52 | + o1 := myfunc.CallFunction() |
| 53 | + if o1 == nil { |
| 54 | + log.Fatal("could not call 'values.myfunc()'") |
| 55 | + } |
| 56 | + fmt.Printf("%s\n", python.PyString_AsString(o1)) |
| 57 | + o1.DecRef() |
| 58 | + |
| 59 | + // modify 'test.ival' and 'test.sval' |
| 60 | + { |
| 61 | + pyival := python.PyInt_FromLong(ival + 1000) |
| 62 | + module.SetAttrString("ival", pyival) |
| 63 | + pyival.DecRef() |
| 64 | + |
| 65 | + pysval := python.PyString_FromString(python.PyString_AsString(sval) + " is the answer") |
| 66 | + module.SetAttrString("sval", pysval) |
| 67 | + pysval.DecRef() |
| 68 | + } |
| 69 | + |
| 70 | + o2 := myfunc.CallFunction() |
| 71 | + if o2 == nil { |
| 72 | + log.Fatal("could not call 'values.myfunc()'") |
| 73 | + } |
| 74 | + fmt.Printf("%s\n", python.PyString_AsString(o2)) |
| 75 | + o2.DecRef() |
| 76 | +} |
0 commit comments