Skip to content

Repository files navigation

Go-Python-Runner :go-python-runner:GoDoc

Go-Python-Runner is a library that runs Python code in isolation.

It runs a python script in an isolated environment (virtual environment) via a go wrapper. It will install dependecies, using one of the following package managers with the following order:

  1. uv (using uv.lock + pyproject.toml)
  2. Poetry (using pyproject.toml)
  3. pipenv (using Pipfile)
  4. pip & venv (using requirements.txt)

Usage

Create virtual environment

python.SetupVirtualEnv("/path/to/python/script/")

This will create a vitual enviroment given the existence of proper files (pyproject.toml, Pipfile or requirements.txt).

Cleanup virtual environment

python.CleanUpVirtualEnv("/path/to/python/script/")

This will delete the .venv directory if exists.

Run python script inside virtual environment

out, err:=python.ExecutePython("/path/to/python/script/", "/path/to/python/script/script.py")

This will run a python script called script.py inside the virtual environment, using the proper command, analyzing files existence.

Alternatively, it is possible to get an instance for *exec.Cmd which can be handled independently.

cmd:=python.GetPythonRunCommand("/path/to/python/script/", "/path/to/python/script/script.py")
out, err:=cmd.CombinedOutput()

or

cmd:=python.GetPythonRunCommand("/path/to/python/script/", "/path/to/python/script/script.py")
err:=cmd.Run()

or

cmd:=python.GetPythonRunCommand("/path/to/python/script/", "/path/to/python/script/script.py")
err:=cmd.Start()
err=cmd.Wait()

Complete example

package main
import (
"fmt""os"
python "github.com/zoispag/go-python-runner/v2/python"
)
funcmain() {
python.SetupVirtualEnv("/path/to/python/script/")
out, err:=python.ExecutePython("/path/to/python/script/", "/path/to/python/script/script.py")
iferr!=nil {
log.Error(fmt.Sprintf("Encountered error: %s", err.Error()))
}
log.Info(string(out))
}

Note: go-python-runner will not install the python package managers. See below for installation instructions.

Python package managers

Contribute

To run:

go run .
with Debug mode:
GO_DEBUG_MODE=on go run main.go

To build as a binary:

go build .

and execute the produced binary with

./go-python-runner

About

Runs python code inside a virtual environment

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages