-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathpython.go
More file actions
101 lines (84 loc) · 1.97 KB
/
Copy pathpython.go
File metadata and controls
101 lines (84 loc) · 1.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package python
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
)
type Python interface {
GetExeName() string
GetExePath() (string, error)
AddPythonPath(p string)
PythonCmd(args ...string) (*exec.Cmd, error)
PythonCmd2(args []string) (*exec.Cmd, error)
}
type python struct {
pythonHome string
pythonPath []string
}
type PythonOpt func(o *python)
func WithPythonHome(home string) PythonOpt {
return func(o *python) {
o.pythonHome = home
}
}
func NewPython(opts ...PythonOpt) Python {
ep := &python{}
for _, o := range opts {
o(ep)
}
return ep
}
func (ep *python) GetExeName() string {
suffix := ""
if runtime.GOOS == "windows" {
suffix = ".exe"
} else {
suffix = "3"
}
return "python" + suffix
}
func (ep *python) GetExePath() (string, error) {
if ep.pythonHome == "" {
p, err := exec.LookPath(ep.GetExeName())
if err != nil {
return "", fmt.Errorf("failed to determine %s path: %w", ep.GetExeName(), err)
}
return p, nil
} else {
var p string
if runtime.GOOS == "windows" {
p = filepath.Join(ep.pythonHome, ep.GetExeName())
} else {
p = filepath.Join(ep.pythonHome, "bin", ep.GetExeName())
}
if _, err := os.Stat(p); err != nil {
return "", fmt.Errorf("failed to determine %s path: %w", ep.GetExeName(), err)
}
return p, nil
}
}
func (ep *python) AddPythonPath(p string) {
ep.pythonPath = append(ep.pythonPath, p)
}
func (ep *python) PythonCmd(args ...string) (*exec.Cmd, error) {
return ep.PythonCmd2(args)
}
func (ep *python) PythonCmd2(args []string) (*exec.Cmd, error) {
exePath, err := ep.GetExePath()
if err != nil {
return nil, err
}
cmd := exec.Command(exePath, args...)
cmd.Env = os.Environ()
if ep.pythonHome != "" {
cmd.Env = append(cmd.Env, fmt.Sprintf("PYTHONHOME=%s", ep.pythonHome))
}
if len(ep.pythonPath) != 0 {
pythonPathEnv := fmt.Sprintf("PYTHONPATH=%s", strings.Join(ep.pythonPath, string(os.PathListSeparator)))
cmd.Env = append(cmd.Env, pythonPathEnv)
}
return cmd, nil
}