Skip to main content

Python worker for pyproc - Call Python from Go without CGO

Project description

pyproc-worker

Python worker implementation for pyproc - Call Python from Go without CGO or microservices.

Installation

pip install pyproc-worker

Quick Start

Create a Python worker with your functions:

from pyproc_worker import expose, run_worker

@expose
def predict(req):
    """Your ML model or Python logic here"""
    return {"result": req["value"] * 2}

@expose
def process_data(req):
    """Process data with Python libraries"""
    import pandas as pd
    df = pd.DataFrame(req["data"])
    return df.describe().to_dict()

if __name__ == "__main__":
    run_worker()

Then call it from Go using pyproc:

pool, _ := pyproc.NewPool(pyproc.PoolOptions{
    Config: pyproc.PoolConfig{
        Workers:     4,
        MaxInFlight: 10,
    },
    WorkerConfig: pyproc.WorkerConfig{
        SocketPath:   "/tmp/pyproc.sock",
        PythonExec:   "python3",
        WorkerScript: "worker.py",
    },
}, nil)

pool.Start(ctx)
defer pool.Shutdown(ctx)

// Call Python function
input := map[string]interface{}{"value": 42}
var output map[string]interface{}
pool.Call(ctx, "predict", input, &output)

Features

  • Simple decorator-based API - Just use @expose to make functions callable
  • Automatic serialization - Handles JSON serialization/deserialization
  • Built-in health checks - Health endpoint automatically exposed
  • Graceful shutdown - Proper cleanup on exit
  • Logging support - Structured logging with configurable levels

API Reference

@expose Decorator

Makes a Python function callable from Go:

@expose
def my_function(req):
    # req is a dict containing the request data
    # Return a dict that will be sent back to Go
    return {"result": "success"}

run_worker(socket_path=None)

Starts the worker and listens for requests:

if __name__ == "__main__":
    # Socket path from environment or command line
    run_worker()
    
    # Or specify explicitly
    run_worker("/tmp/my-worker.sock")

Environment Variables

  • PYPROC_SOCKET_PATH - Unix domain socket path
  • PYPROC_LOG_LEVEL - Logging level (debug, info, warning, error)

Examples

Machine Learning Model

import pickle
from pyproc_worker import expose, run_worker

# Load model at startup
with open("model.pkl", "rb") as f:
    model = pickle.load(f)

@expose
def predict(req):
    features = req["features"]
    prediction = model.predict([features])[0]
    
    return {
        "prediction": int(prediction),
        "confidence": float(model.predict_proba([features])[0].max())
    }

if __name__ == "__main__":
    run_worker()

Data Processing

import pandas as pd
from pyproc_worker import expose, run_worker

@expose
def analyze_csv(req):
    df = pd.DataFrame(req["data"])
    
    return {
        "mean": df.mean().to_dict(),
        "std": df.std().to_dict(),
        "correlation": df.corr().to_dict()
    }

if __name__ == "__main__":
    run_worker()

Async Operations

import asyncio
from pyproc_worker import expose, run_worker

@expose
async def fetch_data(req):
    url = req["url"]
    # Async operations work automatically
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            data = await response.json()
    
    return {"data": data}

if __name__ == "__main__":
    run_worker()

Development

Running Tests

# Install dev dependencies
pip install -e .[dev]

# Run tests
pytest

Building from Source

git clone https://github.com/YuminosukeSato/pyproc
cd pyproc/worker/python
pip install -e .

License

Apache 2.0 - See LICENSE for details.

Links

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pyproc_worker-0.1.0.tar.gz (6.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pyproc_worker-0.1.0-py3-none-any.whl (6.4 kB view details)

Uploaded Python 3

File details

Details for the file pyproc_worker-0.1.0.tar.gz.

File metadata

  • Download URL: pyproc_worker-0.1.0.tar.gz
  • Upload date:
  • Size: 6.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.10.0

File hashes

Hashes for pyproc_worker-0.1.0.tar.gz
Algorithm Hash digest
SHA256 467d548e295889fbd1bad251f0008c55b2f796c05d7fe195a2f516588b0091ec
MD5 abd0b36507747f93bd0c13e0020e788a
BLAKE2b-256 396eaf018d504d52451a7fa141fd400637b03d6b010b11f4c2df185e469d5ac9

See more details on using hashes here.

File details

Details for the file pyproc_worker-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: pyproc_worker-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 6.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.10.0

File hashes

Hashes for pyproc_worker-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 86e0e90f1d7469f0fbd7cce3f593d93ce3fb0b3135585ee25c7e17a178430e38
MD5 f0d3efbd7fe0172726cf2d469b21e17a
BLAKE2b-256 9ce89a6b9c32215a5dfee01174ddf02ac83ef0b40b0b30a562e744a892165310

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page