gopy

package module
v0.9.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 8, 2023 License: MIT Imports: 4 Imported by: 0

README

go-python

Call Python Functions from Go

Runtime Environment

  • Python 3.7.x
  • pkg-config
  • set PKG_CONFIG_PATH and LD_LIBRARY_PATH, e.g.
    export PKG_CONFIG_PATH=/home/xxx/anaconda3/envs/py37/lib/pkgconfig:$PKG_CONFIG_PATH
    export LD_LIBRARY_PATH=/home/xxx/anaconda3/envs/py37/lib:$LD_LIBRARY_PATH
    

Usage

  • import package
    import gopy "github.com/Jinglever/go-python"
    
  • call python function, refer to example_test.go
    cancelEnv, err := gopy.InitPythonEnv()
    if err != nil {
    	panic(err)
    }
    defer cancelEnv()
    
    adapter, cancelAdapter, err := gopy.NewModuleAdapter(
    	"my_module",
    	[]string{"example"},
    )
    if err != nil {
    	panic(err)
    }
    defer cancelAdapter()
    
    outputStr, err := adapter.CallFunc("my_func", `{"name": "gopy"}`)
    if err != nil {
    	panic(err)
    }
    

Dev Environment

  • set vscode setting, e.g.
    {
    	"settings": {
    	"go.toolsEnvVars": {
    		"PATH": "/home/xxx/.gvm/gos/go1.19/bin:/home/xxx/anaconda3/envs/py37/bin:/usr/bin:${env:PATH}",
    		"PKG_CONFIG_PATH": "/home/xxx/anaconda3/envs/py37/lib/pkgconfig:${env:PKG_CONFIG_PATH}",
    		"LD_LIBRARY_PATH": "/home/xxx/anaconda3/envs/py37/lib:${env:LD_LIBRARY_PATH}"
    	}
    }
    

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func InitPythonEnv

func InitPythonEnv() (context.CancelFunc, error)

InitPythonEnv : 初始化python3环境 Attention: 由于python3的GIL机制, python3环境只能在主线程中初始化,否则会导致python3.Py_Initialize()失败; 该函数返回一个取消函数,用于释放python3环境; 注意:如果没有在其它地方初始化python3环境,那么应该调用该函数完成初始化, 并且本函数只能调用一次。

func InsertPythonPaths

func InsertPythonPaths(paths []string)

func LockPythonRuntime

func LockPythonRuntime() context.CancelFunc

LockPythonRuntime : 锁定python3运行时 包括: 1. 锁定当前线程 2. 申请GIL, 确保当前线程成为python主线程 返回一个取消函数, 用于释放GIL和解锁当前线程

Types

type ModuleAdapter

type ModuleAdapter struct {
	// contains filtered or unexported fields
}

ModuleAdapter : 模块接合器

func NewModuleAdapter

func NewModuleAdapter(
	moduleName string,
	pythonPaths []string,
) (*ModuleAdapter, context.CancelFunc, error)

NewModuleAdapter : 创建模块接合器 moduleName: 模块名称 pythonPaths: 需要插入到python3环境的sys.path中的路径列表 返回一个模块接合器, 以及一个取消函数, 用于释放模块接合器

func (*ModuleAdapter) CallFunc

func (adapter *ModuleAdapter) CallFunc(
	funcName string,
	inputStr string,
) (string, error)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL