install.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. # Copyright (c) 2024 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import os
  15. import subprocess
  16. import sys
  17. import tempfile
  18. def install_packages_from_requirements_file(
  19. requirements_file_path, pip_install_opts=None
  20. ):
  21. # TODO: Constraints can be applied here to ensure a safe installation.
  22. # For example, it is best to prevent installing a different version of a
  23. # distribution for an already loaded package, as that could lead to
  24. # problems.
  25. return subprocess.check_call(
  26. [
  27. sys.executable,
  28. "-m",
  29. "pip",
  30. "install",
  31. *(pip_install_opts or []),
  32. "-r",
  33. requirements_file_path,
  34. ]
  35. )
  36. def install_packages(requirements, pip_install_opts=None):
  37. with tempfile.NamedTemporaryFile("w", suffix=".txt", delete=False) as f:
  38. for req in requirements:
  39. f.write(req + "\n")
  40. reqs_file_path = f.name
  41. try:
  42. return install_packages_from_requirements_file(
  43. reqs_file_path, pip_install_opts=pip_install_opts
  44. )
  45. finally:
  46. os.unlink(reqs_file_path)
  47. def uninstall_packages(pkgs, pip_uninstall_opts=None):
  48. return subprocess.check_call(
  49. [
  50. sys.executable,
  51. "-m",
  52. "pip",
  53. "uninstall",
  54. "-y",
  55. *(pip_uninstall_opts or []),
  56. *pkgs,
  57. ]
  58. )