1
0

utils.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. # Copyright 2021-2025 Avaiga Private Limited
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
  4. # the License. You may obtain a copy of the License at
  5. #
  6. # http://www.apache.org/licenses/LICENSE-2.0
  7. #
  8. # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
  9. # an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
  10. # specific language governing permissions and limitations under the License.
  11. import os
  12. import platform
  13. import subprocess
  14. import sys
  15. def _bytes_to_str(b: bytes):
  16. return str(b, "latin-1" if platform.system() == "Windows" else "utf-8")
  17. def _run_template(taipy_path, cwd, main_path, time_out=30):
  18. """Run the templates on a subprocess and get stdout after timeout"""
  19. env = {"PYTHONPATH": taipy_path}
  20. if platform.system() == "Windows":
  21. env.update(os.environ)
  22. with subprocess.Popen(
  23. [sys.executable, main_path],
  24. stdout=subprocess.PIPE,
  25. stderr=subprocess.PIPE,
  26. cwd=cwd,
  27. env=env,
  28. ) as proc:
  29. try:
  30. stdout, stderr = proc.communicate(timeout=time_out)
  31. except subprocess.TimeoutExpired:
  32. proc.kill()
  33. stdout, stderr = proc.communicate()
  34. # Print the error if there is any (for debugging)
  35. if stderr := _bytes_to_str(stderr):
  36. print(stderr) # noqa: T201
  37. return _bytes_to_str(stdout)