python.go 1022 B

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