Skip to content

Latest commit

 

History

History
111 lines (79 loc) · 3.02 KB

File metadata and controls

111 lines (79 loc) · 3.02 KB

GPython Engine · Python Script Engine

Go Version Engine Type

Pure-Go Python 3.4 subset script engine based on gpython

中文 · English · 日本語


Overview

The GPython engine uses the go-python/gpython library to provide Python 3.4 subset scripting capabilities for Go applications. Zero CPython dependency, pure Go implementation, cross-platform compilation without barriers.

Engine Characteristics

Feature Description
Library github.com/go-python/gpython v0.2.0
Language Version Python 3.4 subset
Standard Library Built-in sys, time, math, and other native modules
Thread Safety Dual-lock pattern (RWMutex + execMutex)
Hot Reload Supports StartWatch / StopWatch
Type Constant scriptEngine.GPythonType

Installation

go get github.com/tx7do/go-scripts/gpython

Quick Start

package main

import (
    "context"
    "fmt"
    "log"

    scriptEngine "github.com/tx7do/go-scripts"
    _ "github.com/tx7do/go-scripts/gpython" // Register the GPython engine
)

func main() {
    eng, err := scriptEngine.NewScriptEngine(scriptEngine.GPythonType)
    if err != nil {
        log.Fatal(err)
    }
    defer eng.Close()

    ctx := context.Background()
    if err := eng.Init(ctx); err != nil {
        log.Fatal(err)
    }

    // Inject host variables
    _ = eng.RegisterGlobal("name", "world")

    // Register host functions
    _ = eng.RegisterFunction("greet", func(name string) string {
        return fmt.Sprintf("Hello, %s!", name)
    })

    // Execute Python script
    result, _ := eng.ExecuteString(ctx, "hello.py", `greet(name)`)
    fmt.Println(result)
}

API Reference

Method Description
Init(ctx) Creates gpython interpreter context and main module
Close() Closes interpreter, releases resources
LoadString(ctx, name, code) Compiles Python source and enqueues for execution
Execute(ctx) Sequentially executes all queued scripts
ExecuteString(ctx, name, code) Compiles and immediately executes inline Python code
RegisterGlobal(name, value) Injects Go value as Python global variable
RegisterFunction(name, fn) Registers Go function as Python callable
CallFunction(ctx, name, args...) Calls a Python function
RegisterModule(name, module) Registers a module (keys mapped as modulename_keyname globals)
StartWatch(ctx, key) Starts script hot-reload watching
StopWatch(key) Stops hot-reload watching

Testing

cd gpython && go test -v ./...

Related Documentation

License

MIT License