fx/pkg/reducer/python.go

47 lines
799 B
Go
Raw Normal View History

2022-04-18 20:00:17 +00:00
package reducer
import (
_ "embed"
"fmt"
"os/exec"
)
func CreatePython(bin string, args []string) *exec.Cmd {
2022-04-18 20:57:05 +00:00
cmd := exec.Command(bin, "-c", python(args))
2022-04-18 20:00:17 +00:00
return cmd
}
//go:embed reduce.py
var templatePython string
2022-04-18 20:57:05 +00:00
func python(args []string) string {
2022-04-18 20:00:17 +00:00
rs := "\n"
for i, a := range args {
rs += "try:"
switch {
case a == ".":
rs += `
x = x
`
default:
rs += fmt.Sprintf(
`
2022-04-18 20:57:05 +00:00
f = (lambda x: (%v))(x)
2022-04-18 20:00:17 +00:00
x = f(x) if callable(f) else f
`, a)
}
// Generate a beautiful error message.
rs += "except Exception as e:\n"
pre, post, pointer := trace(args, i)
rs += fmt.Sprintf(
` sys.stderr.write('\n {} {} {}\n %v\n\n{}\n'.format(%q, %q, %q, e))
sys.exit(1)`,
pointer,
pre, a, post,
)
rs += "\n"
}
return fmt.Sprintf(templatePython, rs)
}