-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpython.go
More file actions
62 lines (51 loc) · 1.47 KB
/
python.go
File metadata and controls
62 lines (51 loc) · 1.47 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
package main
import (
"fmt"
"github.com/pkg/errors"
"io/ioutil"
"os"
"os/exec"
)
func saveFile(filename string, fileData []byte) error {
return ioutil.WriteFile(getFullFileName(filename), fileData, 0644)
}
func deleteFile(filename string) error {
return os.Remove(filename)
}
func convertScript(pyscript string) ([]byte, error) {
cmd := exec.Command("jupyter", "nbconvert", "--to", "script", getFullFileName(pyscript))
return runCommand(cmd)
}
func compile(filename string) ([]byte, error) {
cmd := exec.Command("python", "-m", "compileall", getFullFileName(filename))
return runCommand(cmd)
}
func readFile(filename string) ([]byte, error) {
return ioutil.ReadFile(getFullFileName(filename))
}
func runCommand(cmd *exec.Cmd) ([]byte, error) {
return cmd.Output()
}
func getFullFileName(fileName string) string {
return fmt.Sprintf("/tmp/%s", fileName)
}
func processScript(requestId string, data []byte) ([]byte, error) {
var err error
var rb []byte
if err = saveFile(requestId+".ipynb", data); err != nil {
return nil, errors.WithStack(err)
}
if rb, err = convertScript(requestId + ".ipynb"); err != nil {
return nil, errors.WithStack(err)
}
//if rb, err = compile(requestId + ".py"); err != nil {
// return nil, errors.WithStack(err)
//}
if rb, err = readFile(requestId + ".py"); err != nil {
return nil, errors.WithStack(err)
}
_ = deleteFile(requestId + ".ipynb")
_ = deleteFile(requestId + ".py")
_ = deleteFile(requestId + ".pyc")
return rb, nil
}