Last active
November 20, 2023 08:31
-
-
Save raszia/8def9d9bb0420054a4dc00197a841fd1 to your computer and use it in GitHub Desktop.
Python script inside Golang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
/* | |
#cgo CFLAGS: -I/usr/include/python3.8 | |
#cgo LDFLAGS: -lpython3.8 | |
#include <Python.h> | |
*/ | |
import "C" | |
import ( | |
"fmt" | |
"unsafe" | |
) | |
func main() { | |
// Initialize the Python interpreter | |
C.Py_Initialize() | |
// Create a Python module object for the script you want to run | |
module := C.PyImport_ImportModule("example") | |
if module == nil { | |
// Handle error when the module could not be imported | |
fmt.Println("Failed to import module") | |
return | |
} | |
// Call the Python function from the module | |
function := C.PyObject_GetAttrString(module, "my_func") | |
result := C.PyObject_CallObject(function, nil) | |
if result == nil { | |
// Handle error when the function call failed | |
fmt.Println("Failed to call function") | |
return | |
} | |
// Convert the result to a string and print it | |
cStr := C.PyUnicode_AsUTF8(result) | |
goStr := C.GoString(cStr) | |
fmt.Println(goStr) | |
// Release Python objects and finalize the interpreter | |
C.Py_DecRef(result) | |
C.Py_DecRef(function) | |
C.Py_DecRef(module) | |
C.Py_Finalize() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In order to run a Python script inside Golang without using the Python interpreter, you can use the Cgo package to call the Python C API from your Golang code.
In this example, we first initialize the Python interpreter using C.Py_Initialize(). Then, we import the Python module that contains the script we want to run using C.PyImport_ImportModule(). Next, we call the Python function from the module using C.PyObject_GetAttrString() and C.PyObject_CallObject(). Finally, we convert the result to a Golang string and print it, and then we release all Python objects and finalize the interpreter using C.Py_DecRef() and C.Py_Finalize().
Note that you will need to modify the #cgo directives in the comments at the top of the file to match the path of your Python installation. Additionally, you will need to replace "example" with the name of your Python module, and "my_func" with the name of the function you want to call.