python.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package service
  2. import (
  3. "time"
  4. "github.com/langgenius/dify-sandbox/internal/core/runner/python"
  5. runner_types "github.com/langgenius/dify-sandbox/internal/core/runner/types"
  6. "github.com/langgenius/dify-sandbox/internal/static"
  7. "github.com/langgenius/dify-sandbox/internal/types"
  8. )
  9. type RunCodeResponse struct {
  10. Stderr string `json:"error"`
  11. Stdout string `json:"stdout"`
  12. }
  13. func RunPython3Code(code string, preload string, options runner_types.RunnerOptions) *types.DifySandboxResponse {
  14. if err := checkOptions(options); err != nil {
  15. return types.ErrorResponse(-400, err.Error())
  16. }
  17. timeout := time.Duration(
  18. static.GetDifySandboxGlobalConfigurations().WorkerTimeout * int(time.Second),
  19. )
  20. runner := python.PythonRunner{}
  21. stdout, stderr, done, err := runner.Run(
  22. code, timeout, nil, preload, options,
  23. )
  24. if err != nil {
  25. return types.ErrorResponse(-500, err.Error())
  26. }
  27. stdout_str := ""
  28. stderr_str := ""
  29. defer close(done)
  30. defer close(stdout)
  31. defer close(stderr)
  32. for {
  33. select {
  34. case <-done:
  35. return types.SuccessResponse(&RunCodeResponse{
  36. Stdout: stdout_str,
  37. Stderr: stderr_str,
  38. })
  39. case out := <-stdout:
  40. stdout_str += string(out)
  41. case err := <-stderr:
  42. stderr_str += string(err)
  43. }
  44. }
  45. }