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:
- Poetry (using
pyproject.toml
) - PyFlow (using
pyproject.toml
) - pipenv (using
Pipfile
) - pip & venv (using
requirements.txt
)
python.SetupVirtualEnv("/path/to/python/script/")
This will create a vitual enviroment given the existence of proper files (pyproject.toml
, Pipfile
or requirements.txt
).
python.CleanUpVirtualEnv("/path/to/python/script/")
This will delete the .venv
directory if exists. In case of pyflow, it will also delete the __pypackages__
directory.
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()
package main
import (
"fmt"
"os"
python "github.com/zoispag/go-python-runner/python"
)
func main() {
python.SetupVirtualEnv("/path/to/python/script/")
out, err := python.ExecutePython("/path/to/python/script/", "/path/to/python/script/script.py")
if err != 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.
go run .
GO_DEBUG_MODE=on go run main.go
go build .
and execute the produced binary with
./go-python-runner