-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpyprocexec.go
101 lines (85 loc) · 1.98 KB
/
pyprocexec.go
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 jumpboot
import (
"bufio"
_ "embed"
"encoding/base64"
"encoding/json"
"errors"
"os"
"path/filepath"
)
type ExecOptions struct {
ExecType string `json:"type"`
Command string `json:"code"`
}
type ExecResult struct {
ReturnType string `json:"type"`
Output string `json:"output"`
}
//go:embed modules/pyprocexec/main.py
var pythonExecMain string
type PythonExecProcess struct {
*PythonProcess
}
func (env *Environment) NewPythonExecProcess(environment_vars map[string]string, extrafiles []*os.File) (*PythonExecProcess, error) {
cwd, _ := os.Getwd()
program := &PythonProgram{
Name: "PythonExecProcess",
Path: cwd,
Program: Module{
Name: "__main__",
Path: filepath.Join(cwd, "modules", "main.py"),
Source: base64.StdEncoding.EncodeToString([]byte(pythonExecMain)),
},
Modules: []Module{},
Packages: []Package{},
}
pyProcess, _, err := env.NewPythonProcessFromProgram(program, environment_vars, nil, false)
if err != nil {
return nil, err
}
return &PythonExecProcess{
PythonProcess: pyProcess,
}, nil
}
func (p *PythonExecProcess) Exec(code string) (string, error) {
e := ExecOptions{
ExecType: "exec",
Command: code,
}
// encode the command to JSON
cmd_json, err := json.Marshal(e)
if err != nil {
return "", err
}
// send the command to the Python process
_, err = p.PipeOut.Write([]byte(string(cmd_json) + "\n"))
if err != nil {
return "", err
}
// read the output from the Python process
b, err := bufio.NewReader(p.PipeIn).ReadBytes('\n')
if err != nil {
return "", err
}
// decode the output from JSON
var result ExecResult
err = json.Unmarshal(b, &result)
if err != nil {
return "", err
}
if result.ReturnType == "error" {
return "", errors.New(result.Output)
} else {
return result.Output, nil
}
}
func (p *PythonExecProcess) Close() {
e := ExecOptions{
ExecType: "exit",
Command: "",
}
// encode the command to JSON
cmd_json, _ := json.Marshal(e)
p.PipeOut.Write([]byte(string(cmd_json) + "\n"))
}