Skip to content
This repository was archived by the owner on Aug 10, 2022. It is now read-only.

Commit 133b1e0

Browse files
remicalixtehush-hush
authored andcommitted
Add some examples
1 parent a6de78a commit 133b1e0

File tree

2 files changed

+94
-0
lines changed

2 files changed

+94
-0
lines changed

examples/list/main.go

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
/*
2+
Unless explicitly stated otherwise all files in this repository are licensed
3+
under the $license_for_repo License.
4+
This product includes software developed at Datadog (https://www.datadoghq.com/).
5+
Copyright 2018 Datadog, Inc.
6+
*/
7+
8+
package main
9+
10+
import (
11+
"fmt"
12+
"os"
13+
14+
"github.com/DataDog/go-python3"
15+
)
16+
17+
func main() {
18+
python3.Py_Initialize()
19+
20+
if !python3.Py_IsInitialized() {
21+
fmt.Println("Error initializing the python interpreter")
22+
os.Exit(1)
23+
}
24+
25+
err := printList()
26+
if err != nil {
27+
fmt.Printf("failed to print the python list: %s\n", err)
28+
}
29+
30+
python3.Py_Finalize()
31+
}
32+
33+
func printList() error {
34+
list := python3.PyList_New(5)
35+
36+
if exc := python3.PyErr_Occurred(); list == nil && exc != nil {
37+
return fmt.Errorf("Fail to create python list object")
38+
}
39+
defer list.DecRef()
40+
41+
repr, err := pythonRepr(list)
42+
if err != nil {
43+
return fmt.Errorf("fail to get representation of object list")
44+
}
45+
fmt.Printf("python list: %s\n", repr)
46+
47+
return nil
48+
}
49+
50+
func pythonRepr(o *python3.PyObject) (string, error) {
51+
if o == nil {
52+
return "", fmt.Errorf("object is nil")
53+
}
54+
55+
s := o.Repr()
56+
if s == nil {
57+
python3.PyErr_Clear()
58+
return "", fmt.Errorf("failed to call Repr object method")
59+
}
60+
defer s.DecRef()
61+
62+
return python3.PyUnicode_AsUTF8(s), nil
63+
}

examples/python3/main.go

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/*
2+
Unless explicitly stated otherwise all files in this repository are licensed
3+
under the $license_for_repo License.
4+
This product includes software developed at Datadog (https://www.datadoghq.com/).
5+
Copyright 2018 Datadog, Inc.
6+
*/
7+
8+
package main
9+
10+
import (
11+
"fmt"
12+
"os"
13+
14+
"github.com/DataDog/go-python3"
15+
)
16+
17+
func main() {
18+
i, err := python3.Py_Main(os.Args)
19+
if err != nil {
20+
fmt.Printf("error launching the python interpreter: %s\n", err)
21+
os.Exit(1)
22+
}
23+
if i == 1 {
24+
fmt.Println("The interpreter exited due to an exception")
25+
os.Exit(1)
26+
}
27+
if i == 2 {
28+
fmt.Println("The parameter list does not represent a valid Python command line")
29+
os.Exit(1)
30+
}
31+
}

0 commit comments

Comments
 (0)